• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to Generate Unique Random Numbers?

 
prem kanna
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20494
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic