I am struggling to understand the concept of randomly reading numbers from an array of integers using 'rand()'. I have created a random number generator between 1-3 and want to output an index of an array, then for the generator to randomly output the next generated number from the previous index, until it reaches the end of the array. For example:
'rand()'= 3, 'array[2]'
'rand()' = 2, 'array[4]'
if that makes sense?? etc, etc.
The code I'm currently using just outputs a sequence of random numbers. I have place a 'seed' so I can look at the same sequence.
int main()
{
int arrayTest[20] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20};
srand(4);
for(int i = 0; i < 20; i++)
{
arrayTest[i] = (rand() % 3);
cout << arrayTest[i] << endl;
}
}
I am somewhat guessing at what you really want. But it seems to want to make random increments to an index, and use that index to read from the array in a loop.
So this code just doesn't do anything like you want
arrayTest[i] = (rand() % 3);
It writes (not reads) a random value to an array using a sequential (i.e. non-random) index.
Here's what I think you want
int main()
{
int arrayTest[20] = { ... };
srand(4);
int index = -1;
for(int i = 0; i < 20; i++)
{
index += (rand() % 3) + 1; // add random number from 1 to 3 to index
if (index >= 20) // if index too big for array
index -= 20; // wrap around to beginning of array
cout << arrayTest[index] << endl; // read array at random index, and output
}
}
But I'm not completely sure, in particular the way your testArray
has the numbers 1 to 20 in order is making me a bit suspicious. Maybe if you explain why you want to do whatever you want to do it would be a bit clearer.