# Random Number Array with no dups

## Recommended Posts

AkaToraX    122
Pardon the psuedo code, but hopefully you can understand my logic:
Numbers = new array();
dupfound = false;

for(i=0;i<25;i++){
do{
dupfound=false;
Numbers[i]=random(1,50);
for(j=0;j<i;j++){
if(Numbers[i]==Numbers[j])
dupfound=true;
}
}while(dupfound);
}

I want an array of 25 numbers without any duplicates ranging from 1 to 50. The problem is (especially with the last number) there is no telling how long this loop will run, and sometimes is runs for quite a long time. Imagine the 25th number, each time it tries for a random number, there's about a 50% chance it will grab a dup and have to try again. Can anyone help me come up with a better way to generate my array ensuring no dups, without the flaw in my logic? Thanks!!

##### Share on other sites
SiCrane    11839
Assuming C++, create an array or vector with the numbers 1-50. Use random_shuffle() on the container. Read off the first 25 numbers.

##### Share on other sites
Zahlman    1682
Fill an array with the values from 1 to 50, shuffle it randomly, and then take the first 25.

Alternately, fill an array with values from 1 to 50, and iteratively remove values from it, selecting a random element from the remaining ones.

The specifics depend on both your language of choice and on what you plan to use as an "array".

##### Share on other sites
AkaToraX    122
BINGO!!!!! Making an array of 1-50 , and then shuffling the array is EXACTLY what I need to do! So simple :)

Thanks! :)

##### Share on other sites
dmatter    4826
I recommend the shuffling idea, but just to present a third option. You could insert 25 random numbers between 1 and 50 into a std::set which ensures uniqueness.

##### Share on other sites
SiCrane    11839
Quote:
 Original post by dmatterYou could insert 25 random numbers between 1 and 50 into a std::set which ensures uniqueness.

Which brings you back to the problem of selecting non-repeating random numbers the OP had in the first place.

##### Share on other sites
dmatter    4826
Quote:
Original post by SiCrane
Quote:
 Original post by dmatterYou could insert 25 random numbers between 1 and 50 into a std::set which ensures uniqueness.

Which brings you back to the problem of selecting non-repeating random numbers the OP had in the first place.

True, that doesn't help at all does it.

Shows me up for reading the post too fast, I thought the OP didn't want to have to check for duplicates as it was too slow [rolleyes] Oh well.. back to my cave then.

##### Share on other sites
SiCrane    11839
If it's any consolation, you could use a set for this kind of thing, by filling the set with 1-50 and then removing random elements. Of course, that's rather inefficient compared to the shuffle method, but it's another possibility.