You are here:

# C++/Game Of Life Algorithm

Question
I'm working on a program that implements the game of life algorithm. I am to print a two dimensional array, with a border (that has no values), but has the value 'x' stored in random places within the function.  I was going to use the random function to store the value 'x' into random elements of the array, but I am not sure how to do so.

So my question is, how could I use the random function to store the value 'x' into random elements of the two dimensional array.

Have you tried to use this random function you are asking about? If so you will soon find it is in fact called rand - at least I assume this is the random function you refer to, as this is the C standard library function to obtain a pseudo random number that C++ inherited (that is it is also part of the C++ standard library).

Note I am assuming you are using a fairly modern C++ compiler (you are asking a C++ expert...) - by which I mean one with reasonable support for the ISO/ANSI C++ language standard published in 1998 (that is 9 years ago so is not all that new now so this is not unreasonable). Specifically I will use C++ style 'constructor call' object (variable) initialisation syntax, use C++ specific cast syntax and standard C++ header names for C++ equivalent C library headers.

The C/C++ rand function is very simple - it returns an integer (as an int) between 0 and RAND_MAX. RAND_MAX is a pre-defined value that varies between library implementations, but to be standard compliant should be at least 32767 and is usually a #define macro (as it comes from the C side of life):

int random_value( rand() );

However, if you just use rand as above there are two problems. First the values are not usually in the range we require. For example if your life array has dimensions 10 by 10 then we would want random value between 0 and 9, not 0 and 32767 or greater! Thus we have to scale the returned values, one way is to take the mod N of the random value, where N is one greater than the maximum value we require, for example if N were 10:

int random_value_between_0_and_9( rand() % 10 );

The second problem is that every time the program is run the same sequence of random numbers is produced. To overcome this we have to seed the pseudo random number generator with some value. This operation only needs to be performed _once_ per program execution. The provided function to do this is srand (s for seed):

srand( some_value );

The some_value variable above would be an unsigned int.

The next question you are going to ask is how can we obtain a random value for the seed value, or at least a different one for each execution?

There are several methods to do this but the simplest of them is to use the value returned by the time function:

time_t time_now( time(0) );

The time_t type is an arithmetic type capable of holding the library implementation's best approximation to the current calendar time. Although the standard states the encoding of this value is unspecified (meaning it is up to the implementation) typically it is encoded as the number of seconds since the start of the epoc (the epoc is some specific date and time e.g. 00:00:00 UTC on 1 January 1970). The 0 value passed to time is a pointer to some existing time_t object (variable) which will also be set to the current calendar time unless (as in this case) it is a null pointer value.

As time_t is an arithmetic type it can be converted into an unsigned int:

srand( static_cast<unsigned int>( time(0) );

The static_cast is to keep some compilers quite, as they may issue warnings about loss of precision.

The above statement will seed the pseudo random number generator to a different value each time the time function returns a different value, which will typically be every second.

To use these functions and values include <cstddef> for rand, srand and RAND_MAX and <ctime> for time (or <stddef.h> and <time.h> if using C or old C++ compiler/library implementation).

Now in your specific case you will need to:

- Add #includes for <cstdlib> and <ctime> as appropriate.

- Add a single call to srand, as above, to your program. This call should be positioned so it is called once and once only for each execution of your application.

- For each randomly selected cell create 2 random numbers by calling rand twice - once for the x coordinate and once for the y coordinate. These values will of course need to be scaled, as described above.

- If a chosen cell has already ready been selected (i.e. it is already set to an X) skip using this pair of values and select two more. The random coordinates that chose a previously selected cell should not count against the number of randomly pre-set cells to date.

I shall leave it up to you to put all these pieces together and integrate it into your existing code.

Finally I have just typed in the examples out of my head so may contain the odd mistake or typos. If so I apologise, but hope any such errors are not so bad that you are unable to grasp my intended meaning.

Oh, and have fun...

C++

Volunteer

#### Ralph McArdell

##### Expertise

I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.

##### Experience

My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at http://www.open-std.org/jtc1/sc22/wg21/.

Education/Credentials