Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate 6 different random numbers in java

I want to generate 6 different random numbers by using Math.random and store them into an array. How can I make sure that they are different? I know I need to use for-loop to check the array but how...

This is the range. I only need numbers between 1 and 49. ( 1 + (int) (Math.random() * 49) )

like image 741
coding Avatar asked Nov 26 '22 22:11

coding


2 Answers

In Java 8:

final int[] ints = new Random().ints(1, 50).distinct().limit(6).toArray();

In Java 7:

public static void main(final String[] args) throws Exception {
    final Random random = new Random();
    final Set<Integer> intSet = new HashSet<>();
    while (intSet.size() < 6) {
        intSet.add(random.nextInt(49) + 1);
    }
    final int[] ints = new int[intSet.size()];
    final Iterator<Integer> iter = intSet.iterator();
    for (int i = 0; iter.hasNext(); ++i) {
        ints[i] = iter.next();
    }
    System.out.println(Arrays.toString(ints));
}

Just a little messier. Not helped by the fact that it's pretty tedious to unbox the Set<Integer> into an int[].

It should be noted that this solution should be fine of the number of required values is significantly smaller than the range. As 1..49 is quite a lot larger than 6 you're fine. Otherwise performance rapidly degrades.

like image 175
Boris the Spider Avatar answered Dec 15 '22 05:12

Boris the Spider


Create a list containing the numbers 1 to 49.

Create a random number x between 0 and the size of the list, take the number being at index x in the list, and remove it from the list.

Repeat the previous step 5 times. And you're done. Note that java.util.Random has a nextInt(int max) method that you should use instead of Math.random().

Note regarding performance: this solution has an advantage compared to the "try until you get 6 different numbers" various solutions: it runs in a O(n) time. It doesn't matter much for 6 unique numbers out of 50, but if you want to get 48 or 49 unique random numbers out of 50, you'll start seeing a difference, because you might have to generate many random numbers before getting one that isn't already in the set.

EDIT:

to reduce the cost induced by the removal of the elements in the list, you could instead simply replace the element at index x with the last element of the list (and at the second iteration, with the element at size - 2, etc.)

like image 25
JB Nizet Avatar answered Dec 15 '22 04:12

JB Nizet