Hi Yoshima, there are a few ways to go about this, I'll show you what I think is the easiest. First you need to import the headers <stdlib.h> and <time.h> (the reason behind needing time will be clear in a moment). Every time you generate a random number in windows, it uses a pre-determined algorithm to produce the number. This means the "Random" number will be the same every time you run your program. In order to make your "random" number truely random, we will use the current time as the random seed and then use some basic algebra to reduce the number down to the range we need it in. In this case we will generate a random number between 0 and 3 that we will use as an index for your array. Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
#include <stdlib.h>
#include <time.h>
int main ()
{
srand ( time(NULL) ); //initialize the random seed
constchar arrayNum[4] = {'1', '3', '7', '9'};
int RandIndex = rand() % 4; //generates a random number between 0 and 3
cout << arrayNum[RandIndex];
}
@firedraco. Nice! How big is that magic bag of functions? I'll be looking into it!
The need to randomize elements has come up in my game projects for Scrabble (scramble the tile pool after filling it with the required distribution of letters) and in minesweeper to place the mines on the field. My take at re-inventing the wheel:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// places randomly selected element at end of array
// then shrinks array by 1 element. Done when only 1 element is left
void RandomElements(int* v, int n)
{
int temp = 0;
int ridx = n-1;
for(int j=(n-1); j>1; j--)// one pass through array
{
ridx = rand()%(j+1);// index = 0 to j
temp = v[ridx];// value will be moved to end element
v[ridx] = v[j];// end element value in random spot
v[j] = temp;// selected element moved to end. This value is final
}
return;
}