# Random Number Array with no dups

This topic is 3931 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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=random(1,50);
for(j=0;j<i;j++){
if(Numbers==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
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
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
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
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
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
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
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.

1. 1
Rutin
24
2. 2
3. 3
JoeJ
18
4. 4
5. 5

• 38
• 23
• 13
• 13
• 17
• ### Forum Statistics

• Total Topics
631710
• Total Posts
3001846
×