James Harris James Harris - 2 months ago 10
Java Question

Generate 5 sets of 6 random numbers within range 1-49, by making sure there aren’t any duplicates in each set?

I am making a program that will generate 5 sets of 6 random numbers to be used in the lottery however at the moment when the sets of numbers are printed they contain duplicates. How can I make it so every number in each set is unique? (Note each set should be ordered in ascending order from lowest to highest)

import java.util.Arrays;

public class tasksTest {

public static void main(String[] args) {


System.out.println("Your lottery numbers are:");

for(int i=1; i<6; i++){

int[]lotteryNumbers = new int[6];

for(int ii = 0; ii < lotteryNumbers.length; ii++){
lotteryNumbers[ii] = (int)(Math.random()*49 + 1);
}

Arrays.sort(lotteryNumbers);
System.out.println(Arrays.toString(lotteryNumbers));
}
}
}

Answer

You can use sets:

Set<Integer> allNumbers = new HashSet<>();
for (int i = 1; i < 6; i++)
{
  Set<Integer> set = new HashSet<>();
  while (set.size() < 6)
  {
    int random = (int) (Math.random() * 49 + 1);
    if (allNumbers.add(random))
    {
      set.add(random);
    }
  }
  Integer[] array = set.toArray(new Integer[] {});
  Arrays.sort(array);
  System.out.println(Arrays.toString(array));  
}
Comments