James Harris - 1 year ago 65
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 static void main(String[] args) {

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));
}
}
}
``````

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