【问题标题】:Random numbers in an array without duplicates没有重复的数组中的随机数
【发布时间】:2021-02-17 17:51:49
【问题描述】:

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

我用的是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. 

【问题讨论】:

  • 你以前用过hashmap吗?我会使用 hashmap 来存储你的值,当你使用 nextInt 创建值时,你可以检查你的地图以查看是否已经创建了值
  • r.nextInt(lotteryMax-min) + min 您的号码池可能非常小。只需将所有可能的数字添加到数组/列表中,然后随机播放并获取前六个值。这将保证没有重复...

标签: java arrays set


【解决方案1】:

您遇到问题的原因是因为您递归调用 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 高于你需要的数字

【讨论】:

    【解决方案2】:

    看看这个

    public void drawLotto(){
        Random random = new Random();
    
        while(lotteryDraw.size()<6) {
            lotteryDraw.add(random.nextInt(max-min)+min);
        }
    
        lotteryDraw.forEach(System.out::println);
    }
    

    【讨论】:

      【解决方案3】:

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

      例子:

      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;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-02-27
        • 1970-01-01
        • 1970-01-01
        • 2016-03-01
        • 2020-01-05
        • 2015-01-06
        • 2021-03-31
        相关资源
        最近更新 更多