Generating Unique Random Numbers in Java

后端 未结 21 2577
不思量自难忘°
不思量自难忘° 2020-11-21 07:45

I\'m trying to get random numbers between 0 and 100. But I want them to be unique, not repeated in a sequence. For example if I got 5 numbers, they should be 82,12,53,64,32

21条回答
  •  误落风尘
    2020-11-21 07:59

    I feel like this method is worth mentioning.

       private static final Random RANDOM = new Random();    
       /**
         * Pick n numbers between 0 (inclusive) and k (inclusive)
         * While there are very deterministic ways to do this,
         * for large k and small n, this could be easier than creating
         * an large array and sorting, i.e. k = 10,000
         */
        public Set pickRandom(int n, int k) {
            final Set picked = new HashSet<>();
            while (picked.size() < n) {
                picked.add(RANDOM.nextInt(k + 1));
            }
            return picked;
        }
    

提交回复
热议问题