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

1

u/[deleted] Apr 22 '16

Are you familiar with Sets? What have you tried so far?

3

u/[deleted] Apr 22 '16

import java.util.*; public class Lab1{

public static void main(String[] args) { int SET_SIZE = 4;

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

 Random rand = new Random();

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

 while(set2.size() < SET_SIZE) {
     int num = rand.nextInt(52);
     if(!set1.contains(num)) {
         set2.add(num);
     }
 }

 while(set3.size() < SET_SIZE) {
     int num = rand.nextInt(52);
     if(!set1.contains(num) && !set2.contains(num)) {
         set3.add(num);
     }
 }

 System.out.println("Set1: " + set1);
 System.out.println("Set2: " + set2);
 System.out.println("Set3: " + set3);

} }

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.