Sign in to follow this  
AkaToraX

Random Number Array with no dups

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[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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this