How to generate 6 different random numbers in java

2020-02-06 03:56发布

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

10条回答
贪生不怕死
2楼-- · 2020-02-06 04:32

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

查看更多
欢心
3楼-- · 2020-02-06 04:39

You can use a Set.

Set<Integer> s = new HashSet<>();
while(s.size() != 6){
   s.add(1 + (int) (Math.random() * 49));
}

Integer[] arr = s.toArray(new Integer[s.size()]);

This is enough to do this in your case because the number of distinct random numbers is relatively small compared to the size of the range you generate them.

Otherwise I would go with @JBNizet approach.

查看更多
聊天终结者
4楼-- · 2020-02-06 04:39

Create a variable last; initialize it to 0.

Next, in a loop x from 0 to 5, create a random number between last+1 and 49-6+x. Store this number in a list, and set last to the number generated this way.

You will end up with an ordered list of 6 random numbers in the range of 1..49 with no repeats.

查看更多
Luminary・发光体
5楼-- · 2020-02-06 04:42

in your case n=6

     public static int[] chooseAny(int n){
        int[] lottery = new int[n];
        int[] chooseFrom = new int[49];
        for(int i=1 ; i <= 49 ; i++)
            chooseFrom[i-1] = i;
        Random rand = new Random();
        int N = 49;
        int index;
        for(int i=0 ; i < n ; i++){
            //pick random index
            index = rand.nextInt(N);
            lottery[i] = chooseFrom[index];
            chooseFrom[index] = chooseFrom[N-1];
            N--;
        }
        return lottery;
    }
查看更多
登录 后发表回答