How can I prevent the overlapping random numbers

2020-02-07 03:18发布

How would i prevent duplicating numbers from random numbers. I need to generate 5 numbers between 1 and 9 that are each different. I would often get same numbers like 23334, how can i prevent that? Any help would be great!

    int num2 = (int) Math.round((Math.random()*9) +1);
    int num1 = (int) Math.round((Math.random()*9) +1);
    int num5 = (int) Math.round((Math.random()*9) +1);
    int num3 = (int) Math.round((Math.random()*9) +1);
    int num4 = (int) Math.round((Math.random()*9) +1);

标签: java random
8条回答
▲ chillily
2楼-- · 2020-02-07 03:56

If the number of possible random values is small, you want to use shuffle.

List<Integer> values = IntStream.range(0, 10).boxed().collect(toList());
Collections.shuffle(values);
values = values.subList(0, 5);

If the number of possible random values is large, you want to test adding them to a Set (or the original list if small enough)

Set<Integer> valueSet = new HashSet<>(); 
Random rand = new Random();
while(valuesSet.size() < 5) valuesSet.add(rand.nextInt(9) + 1);
List<Integer> values = new ArrayList<>(valueSet);
Collections.shuffle(values, rand);

Note: you need to shuffle the set as it doesn't preserve order. e.g. the numbers 1,2,3 will always come out in that order with HashSet, not 3,2,1.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2020-02-07 03:57

How about this?

package com.se;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class TestRandom {

    List<Integer> comp = new ArrayList<>();
    int listSize = 20;
    public void doTask() {

        Random ran = new Random();
        int i = 0;
        while(i < listSize){
            int randomNumber = ran.nextInt(80) + 1;

            if(!comp.contains(randomNumber)){
               comp.add(randomNumber);
               i++;
            }
        }

    for(Integer num : comp){
        System.out.println(num);
    }
}

public static void main(String[] args) {
    TestRandom testRandom = new TestRandom();
    testRandom.doTask();
}

}
查看更多
登录 后发表回答