Meaningless Drivel is fun!
The moose likes Java in General and the fly likes Simple Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Simple Question" Watch "Simple Question" New topic

Simple Question

Angelo Watson
Ranch Hand

Joined: Oct 27, 2002
Posts: 39
Im creating a lottery random generator.
How do I go by displaying random numbers between 1-52 without displaying the same number?
Sayed Ibrahim Hashimi
Ranch Hand

Joined: May 17, 2001
Posts: 148
Here's what you can do, create an array with 52 elements and to begin with just go from 1 to 52. So now you have an array with all the possibl numbers that you can select from.
Then you want to enter a for loop, go from 0 to 51, so to begin with you are at 0 then generate a random number between 0 and 51. Swap the 0th element with the element number that you generated. After that is done then move on to 1 and do the same thing. Do this until you reach the end of the array. Depending on how good you want these to be mixed up you can do this whole process more than once.
After you are done then simply start pulling numbers from the front, and you are guarenteed not to get any repeats.
As a side note, if you are mixing an existing List and you don't want to effect its order, then you simply create another array with the numbers 0 through list.size()-1, and you randomize that array then use those values as indecies to the list. So that way you don't disturb the original order of the List.
Hope this helps.

SCJP 1.4<br /><a href="" target="_blank" rel="nofollow"></a>
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
If you use a List rather than an array, you can just use Collections.shuffle(List) to randomize the order. It uses the same algorithm just described by Ibrahim - the advantage is, it's already implemented for you. Note also that there's not really any need to shuffle more than once unless there's some flaw in the random number generator - the algorithm gives all possible permutations an equal chance of occurring.

"I'm not back." - Bill Harding, Twister
Peter den Haan
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
If you're worried about the quality of your random numbers and hence your shuffling, there's an overloaded version that takes a Random. You could use a SecureRandom, for instance.
- Peter
I agree. Here's the link:
subject: Simple Question
It's not a secret anymore!