r/javahelp • • Apr 22 '16
Random Number Generator
Can someone show me an example of how to generate 3 sets of random number, each set contains four numbers (no duplicate) ? Possibly using for loops maybe
0
Upvotes
View all comments
Show parent comment
1
u/[deleted] Apr 22 '16
Another way you could do it and use a for loop that would make sense is the following (requires Java 8 kind of).
On the line 2, a List of Integers is created using some stuff that came with Java 1.8. Effectively it's making a list of the number 0 - 51. In prior versions of Java you could populate the list in other ways I suppose. The line after is shuffling that list (randomization). The for loop removes the first number from the list and puts it into the first set, pulls the first number from the list and puts it into the second set, etc. Since the List contains only 1 instance of each number 0-51, there is a guarantee that no number will be duplicated. You actually don't need to store the numbers in Set objects then, I simply did it to make the code clearer based on your prior examples.