Hello, I need some help filling an array with UNIQUE random numbers. So far I've figured out how to fill an array with random numbers, that's easy, but I'm stuck on how to avoid filling it with duplicate values. I'm assuming that i'll have to use either a linear or binary search function while filling the array, but my attempts so far have failed. Anyone got any idea what i'm doing wrong? Here's my terrible code so far...any help would dearly be appreciated.
I recently had a situation where I had to choose 10 random questions out of a bank of 30. The questions should be unique. There are probably more efficient ways of doing this and there is the potential for an infinite loop (or at least a really long one)
//Pick 10 unique random questions out of a bank of 30
int currentRandInt;
questionNumbers[0] = getRandInt(0,29); //First one's free
for (int i = 1; i < 10; i++)
{
currentRandInt = getRandInt(0,29); //Get a rand int
//Check this rand int against all previous stored values
for int (j = 0; j < i; j++)
{
if(currentRandInt == questionNumbers[i])
{
//If we have a match, get a new rand int and begin again
currentRandInt = getRandInt(0,29);
j = 0; //Here's where the potential for infinite loop is introduced
}
}
//If this is a unique rand int then keep it and proceed to to the next value
questionNumbers[i] = currentRandInt;
}
Substitute in your own random int function, but the logic should be similar.