|
-
September 30th, 2003, 05:08 PM
#1
2D Array & random numbers
I've got a two dimensional array which needs the first and third rows to match. In a "for" loop, I'm creating a random number (0-9)and assigning it to the first element in the array, and then incrementing the column element and repeating the process, giving me four random numbers in row1 (element[0]). Here's what I'm working with:
Code:
int i;
int Game[3][4] = {0};
for (i=0; i<=3; i++)
{
Game[0][i] = rand() % 10;
Game[2][i] = Game[0][i];
}
Is there a way to set one row equal to another without looping through the two as I have here? Also, each time I run this piece of code I get the same "random" numbers. I tried using randomize() and random() but couldn't make it work. I kept getting erros that randomize and random were not declared variables. How can I ensure the numbers I'm getting differ each time?
-
September 30th, 2003, 05:15 PM
#2
You need to seed the random number generator to get a random sequence.
Use: srand( (unsigned)time( NULL ) );
This starts the generator based on the computers clock.
To copy a row in an array yo do need to copy each element individually.
-
September 30th, 2003, 05:19 PM
#3
Just noticed that you initialise the array with { 0 }.
You probably know this, but that only sets Game[0][0] = 0
The remainder of the array will have values that are undetermined, in a debug build, these might be 0, but a release build they could be anything.
-
September 30th, 2003, 05:24 PM
#4
Radomn Numbers
I haven't tried using srand() before. Here's and exmaple I pulled out of a book, which I tried to adapt to my code. I get teh same undeclared variable errors though.
Code:
#include <time.h>
#include <stdlib.h>
#include <iostream.h>
int main()
{
int i;
randomize();
for (i=1; i<5; i++)
{
cout << "\n" << random(10);
}
return 0;
}
-
September 30th, 2003, 05:27 PM
#5
Originally posted by Dave McLelland
Just noticed that you initialise the array with { 0 }.
You probably know this, but that only sets Game[0][0] = 0
Not true. If there are fewer entries in the initialization list than entries in the array, the remaining elements are set to 0.
Regards,
Paul McKenzie
-
September 30th, 2003, 05:34 PM
#6
You are right of course. It says so in the ARM.
Dave Mclelland.
-
September 30th, 2003, 06:08 PM
#7
DEFENDER OF ALL THINGS STL!!!
-
September 30th, 2003, 06:10 PM
#8
Sorry, I don't know what that is or how to use it.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|