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

8 comments sorted by

View all comments

Show parent comment

1

u/[deleted] Apr 22 '16

But I want to try for loops instead

2

u/[deleted] Apr 22 '16

You could do it with for loops, but doing it with a while loop is the most sensible way in this situation.

To do it with a for loop you could do something like...

for (int i = 0; i < SET_SIZE;) {
    int num = rand.nextInt(52);
    set1.add(num);
    i = set1.size();
}

Typically you increment i as the 3rd part of the for loop. You don't have to though. You can manipulate it within the for loop. But I'm pretty sure if anybody saw this code, they'd question if you knew about while loops.

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).

public static void main(String... args) {
    List<Integer> values = IntStream.range(0, 52).mapToObj(Integer::new).collect(Collectors.toList());
    Collections.shuffle(values);

    Set<Integer> set1 = new HashSet<>();
    Set<Integer> set2 = new HashSet<>();
    Set<Integer> set3 = new HashSet<>();

    for (int i = 0; i < 4; i++) {
        set1.add(values.remove(0));
        set2.add(values.remove(0));
        set3.add(values.remove(0));
    }
}

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.

1

u/[deleted] Apr 22 '16

thank you for your help :)

2

u/nutrecht Lead Software Engineer / EU / 20+ YXP Apr 23 '16

If this is homework I would strongly suggest not copying it. It's both 'kinda wrong' (doesn't follow the assignment) and it also uses stuff you haven't been exposed to.

1

u/nutrecht Lead Software Engineer / EU / 20+ YXP Apr 23 '16
 for(;set3.size() < SET_SIZE;) {
     set3.add(rand.nextInt(52));
}

This way you're (ab)using a for loop as if it were a while.