Generating Unique Random Numbers in Java

后端 未结 21 2565
不思量自难忘°
不思量自难忘° 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:52

    you can use boolean array to fill the true if value taken else set navigate through boolean array to get value as per given below

    package study;
    
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    
    /*
    Created By Sachin  Rane on Jul 18, 2018
    */
    public class UniqueRandomNumber {
        static Boolean[] boolArray;
        public static void main(String s[]){
            List integers = new ArrayList<>();
    
    
            for (int i = 0; i < 10; i++) {
                integers.add(i);
            }
    
    
            //get unique random numbers
            boolArray = new Boolean[integers.size()+1];
            Arrays.fill(boolArray, false);
            for (int i = 0; i < 10; i++) {
                System.out.print(getUniqueRandomNumber(integers) + " ");
    
            }
    
        }
    
        private static int  getUniqueRandomNumber(List integers) {
            int randNum =(int) (Math.random()*integers.size());
            if(boolArray[randNum]){
                while(boolArray[randNum]){
                    randNum++;
                    if(randNum>boolArray.length){
                        randNum=0;
                    }
                }
                boolArray[randNum]=true;
                return randNum;
            }else {
                boolArray[randNum]=true;
                return randNum;
            }
    
        }
    
    }
    

提交回复
热议问题