Generating Unique Random Numbers in Java

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

    This is the most simple method to generate unique random values in a range or from an array.

    In this example, I will be using a predefined array but you can adapt this method to generate random numbers as well. First, we will create a sample array to retrieve our data from.

    1. Generate a random number and add it to the new array.
    2. Generate another random number and check if it is already stored in the new array.
    3. If not then add it and continue
    4. else reiterate the step.
    ArrayList sampleList = new ArrayList<>();
    sampleList.add(1);
    sampleList.add(2);
    sampleList.add(3);
    sampleList.add(4);
    sampleList.add(5);
    sampleList.add(6);
    sampleList.add(7);
    sampleList.add(8);
    

    Now from the sampleList we will produce five random numbers that are unique.

    int n;
    randomList = new ArrayList<>();
    for(int  i=0;i<5;i++){
        Random random = new Random();
        n=random.nextInt(8);     //Generate a random index between 0-7
    
        if(!randomList.contains(sampleList.get(n)))
        randomList.add(sampleList.get(n));
        else
            i--;    //reiterating the step
    }
            
    

    This is conceptually very simple. If the random value generated already exists then we will reiterate the step. This will continue until all the values generated are unique.

    If you found this answer useful then you can vote it up as it is much simple in concept as compared to the other answers.

提交回复
热议问题