I want to create a multidimensional array with just two values : 0 or 1.
I use the srand/rand functions but array contains only 0.
Here is the code :
#define NB_LINE 4
#define NB_COLUMN 11
int tab[NB_LINE][NB_COLUMN] ; // global variable
void generate() {
srand((unsigned int)time(NULL));
int n, i, j;
for(n = 0; n < NB_LINE*NB_COLUMN; ++n){
do
{
i = rand() % NB_LINE;
j = rand() % NB_COLUMN;
}
while (tab[i][j] != 0);
tab[i][j] = 1 ;
}
}
I don’t know how to solve this problem ?
thanks !
Edit : Thanks for your answers. Do you think it’s possible with rand() to have juste one “1” per column and others spots contain only 0 ?
Edited question
Yes, of course.
Instead of looping over all lines and all columns setting each individual array element to a random value of
0or1do initialize all array elements to 0 (if they aren’t already); loop over all columns and choose 1 random line and set the corresponding array element to1.Notice I’ve removed the
srand()from thegenerate()function.srand()should be called no more than once per program invocation (to guarantee maximum randomness). The best way to accomplish that is to callsrandfrommain().Also, instead of
iandj, I named the variablesrowandcol.And, I’ve made
taba local variable rather than global. Avoid globals whenever possible: it’s a favor you do yourself. With no globals the information is passed to the function through arguments.