Random Number Array with no dups

Started by
6 comments, last by SiCrane 16 years, 6 months ago
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!!
Advertisement
Assuming C++, create an array or vector with the numbers 1-50. Use random_shuffle() on the container. Read off the first 25 numbers.
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".
BINGO!!!!! Making an array of 1-50 , and then shuffling the array is EXACTLY what I need to do! So simple :)

Thanks! :)
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.
Quote:Original post by dmatter
You 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.
Quote:Original post by SiCrane
Quote:Original post by dmatter
You 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.
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.

This topic is closed to new replies.

Advertisement