How to generate 6 different random numbers in java

后端 未结 10 1310
猫巷女王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:49

    Generate any 6 numbers (not necessarily different). Order them.

    a1 <= a2 <= a3 <= a4 <= a5 <= a6

    Now take these 6 numbers

    a1 < a2 + 1 < a3 + 2 < a4 + 3 < a5 + 4 < a6 + 5

    These 6 are different and random.

    The idea of this construct comes from some combinatorial proofs.

    Its advantage is that it's simple, fast, and deterministic.
    I think the time complexity is O(count*log(count)).
    I wonder if it can be improved.

    import java.util.TreeMap;
    
    public class Test005 {
    
        public static void main(String[] args) {
            int count = 6;
            int min = 1;
            int max = 49;
    
            // random number mapped to the count of its occurrences
            TreeMap mp = new TreeMap();
            for (int i=0; i

提交回复
热议问题