Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!

# How to Generate Unique Random Numbers?

prem kanna
Greenhorn
Posts: 26
Hi all,
How to generate unique random numbers with out repetitions. i have a values between 1 to 9. i want to generate 5 unique random numbers from this 1 to 9. if i am using this code then it will generate a duplicate random numbers. Can any one please solve this problem and give me the solution code.

Piet Verdriet
Ranch Hand
Posts: 266

Rob Spoor
Sheriff
Posts: 20529
54
Please Be Forthright When Cross Posting To Other Sites.

As for your problem, random automatically means non-unique. If you still need both, you will need to store all previous results and regenerate if you generated an existing number. This can cause infinite looping though, because the randomness cannot even guarantee that you will ever generate a new number.

Ilja Preuss
author
Sheriff
Posts: 14112
Originally posted by Rob Prime:

As for your problem, random automatically means non-unique. If you still need both, you will need to store all previous results and regenerate if you generated an existing number. This can cause infinite looping though, because the randomness cannot even guarantee that you will ever generate a new number.

A solution that prevents this problem, and which works especially well for a small range of numbers:

- create an array with all the possible numbers, in your case one with the numbers from 1 to 9
- shuffle the array, using an ordinary random number generator
- use the first (or last) x numbers from the array as your unique random numbers