# A 2-D Array of random numbers that don't repeats itself

This is a discussion on A 2-D Array of random numbers that don't repeats itself within the C Programming forums, part of the General Programming Boards category; I guess i am writing the correct code but still the output is not proper. Here's the algorithm i am ...

1. ## A 2-D Array of random numbers that don't repeats itself

I guess i am writing the correct code but still the output is not proper. Here's the algorithm i am trying-

->generate a random number using rand() inside the array
->using other variables, check if there is the value generated is already assigned to some other slot
-> if not, assign thee vaue to the slot

here's quote of my code-

Code:
```for ( i=0; i<4; i++)
{
for( j=0; j<4; j++)
{
z=(rand()%15)+1;
for ( k=0; k<4; k++)
{
for( l=0; l<4; l++)
{
if (a[k][l]==z)
break;
}
}
}
}```
please suggest necessary changes.

Thank you

2. If the random numbers are within a small range, a simpler solution is to treat the 2D array as one big 1D array, then perform a Fisher-Yates/Knuth shuffle on the array that is pre-populated with the numbers from the range.

3. Originally Posted by Akshay_
please suggest necessary changes.
I assume that you then want to know the minimum that you need to change to get it to do what you want. I.e. you have no interest in any other suggestions.

The minimum would be to:
Add another loop in the middle such that if the number randomly generated is already in use then you generate another.
Generate 16 distinct values for your 4x4 array instead of only 15, which would make it try forever to find a valid last value.
Actually put the randomly chosen value into the array.
Change your break to something that breaks out of both the innermost loops rather than just the one. A flag variable might help there.

Or you could just delete the code you have, do a Fisher-Yates shuffle and use two nested loops to just stick those values into the array.

I also recommend the later option.

Popular pages Recent additions