How to generate 6 different random numbers in java

后端 未结 10 1307
猫巷女王i
猫巷女王i 2020-12-10 21:04

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 t

10条回答
  •  情歌与酒
    2020-12-10 21:38

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

提交回复
热议问题