aspose file tools*
The moose likes Java in General and the fly likes How to Generate Unique Random Numbers? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "How to Generate Unique Random Numbers?" Watch "How to Generate Unique Random Numbers?" New topic
Author

How to Generate Unique Random Numbers?

prem kanna
Greenhorn

Joined: Sep 10, 2008
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

Joined: Feb 25, 2006
Posts: 266
http://forums.sun.com/thread.jspa?threadID=5333288
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19692
    
  20

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
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


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to Generate Unique Random Numbers?