数组中没有重复的随机数

时间:2021-02-17 17:51:49

标签: java arrays set

我知道这个问题已经得到解答,但这些解决方案不适合我的方式,所以我想看看是否有更简单的解决方案。

我使用的是 set 界面,我需要有 6 个随机数,并且 set 界面中不能有重复。

这就是我目前所拥有的,我这样做的方式并不理想并且经常导致崩溃。

public void drawLotto(){ //The validation I have here I know isn't the most effective way and is-
        Random r = new Random();//resource comsuning but this was the only way I could think of doing it.
        int draw[] = new int[6];
        int min = 1;
        for(int i = 0; i < draw.length; i++){
            draw[i] = r.nextInt(lotteryMax-min) + min;
            lotteryDraw.add(draw[i]);
        }
        int size = lotteryDraw.size();
        if(size != 6){
            drawLotto();
        }
        for(int i = 0; i < draw.length; i++){
            System.out.println(draw[i] + " ,");
        }
        System.out.println();
    }
``
Thank you, any help is appreciated. 

3 个答案:

答案 0 :(得分:2)

出现问题的原因是因为您递归调用 drawLotto(),这将依次创建 Random 的新实例。如果 drawLotto() 无法创建正确的列表,它将必须对所有 6 个数字进行完全重试。这可能会导致您的应用程序使用大量内存,从而导致您遇到崩溃

一种方法是不断循环直到找到 6 个唯一的数字:

public void drawLotto(){
    Random r = new Random();
    Set<Integer> draw = new HashSet<>();
    int min = 1;
    int lotteryMax = 50;

    while(draw.size() < 6){
        draw.add(r.nextInt(lotteryMax-min) + min);
    }

    String lotteryDrawing = draw.stream().map(String::valueOf).collect(Collectors.joining(" ,"));

    System.out.println(lotteryDrawing);
}

虽然你必须确保你的lotteryMax高于你需要的数字

答案 1 :(得分:2)

看看这个

public void drawLotto(){
    Random random = new Random();

    while(lotteryDraw.size()<6) {
        lotteryDraw.add(random.nextInt(max-min)+min);
    }

    lotteryDraw.forEach(System.out::println);
}

答案 2 :(得分:0)

如果您想避免重复值,请使用集合。

示例:

public static Set <Integer> drawLotto() { //The validation I have here I know isn't the most effective way and is-
    Random r = new Random(); //resource comsuning but this was the only way I could think of doing it.
    int draw[] = new int[6];
    int min = 1;
    int lotteryMax = 10;
    Set<Integer> lotteryDraw = new HashSet<Integer>();
    for (int i = 0; i < draw.length; i++) {
        draw[i] = r.nextInt(lotteryMax - min) + min;
        lotteryDraw.add(draw[i]);
    }
    int size = lotteryDraw.size();
    if (size != 6) {
        return drawLotto();
    } else {
        return lotteryDraw;
    }
}
相关问题