Win a copy of Functional Reactive Programming this week in the Other Languages forum!

# Simple Question

Angelo Watson
Ranch Hand
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
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.

Jim Yingst
Wanderer
Sheriff
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.

Peter den Haan
author
Ranch Hand
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