【问题标题】:eliminating repeated random numbers [duplicate]消除重复的随机数
【发布时间】:2020-04-28 20:11:07
【问题描述】:

我需要以随机顺序获取数字 0-11,并确保每个数字只获取一次。不过,它仍在向我的 Line2 班级发送相同的号码。如何确保 int 变量 lineChoice 每次都完全不同? 我的问题是 if/else 没有正确确保我没有将已选择的 lineChoice 发送到我的 Line2 类。

for(int i = 0; i < 12; i++){
        //get a random line choice 0-11
        lineChoice = (int)(Math.random() * 11); //0-11;
        //if that number was already chosen
        //get a new random number and add it to the array
        if(randomNumbers.contains(lineChoice)){
            lineChoice = (int)(Math.random() * 11); //0-11;
            randomNumbers.add(lineChoice);
        }else{
            //if not already in array, add to array
            randomNumbers.add(lineChoice);
        } 
        //make a Line based on the random lineChoice number
        line = new Line2(lineChoice);
        //add the line to the string poem
        poem += "\n" + line + "\n\n\n";                        
    } 

【问题讨论】:

    标签: java arrays arraylist random


    【解决方案1】:

    您可以创建一个从 1 到 11 的 Int 列表,然后将其随机化。

     List<Integer> ints = IntStream.range(1,12).boxed().collect(Collectors.toList());
            Collections.shuffle(ints);
            System.out.println(ints);
    
    

    【讨论】:

      【解决方案2】:

      这是推荐的做法。

      int [] nums = {0,1,2,3,4,5,6,7,8,9,10,11};
      
      for (int i = nums.length-1; i >= 0; i--) {
          int s = (int)(Math.random()*(i+1));
          System.out.println(nums[s]); // here is where you get your number
          nums[s] = nums[i];
      }  
      

      或者如果你只是想洗牌。

       for (int i = nums.length-1; i >= 0; i--) {
          int s = (int)(Math.random()*(i+1));
          int t = nums[s];
          nums[s] = nums[i];
          nums[i] = t;
      }
      
      

      【讨论】:

        【解决方案3】:

        你需要一个数组来这样做,

        按照以下代码,您只需生成总共 11 个(共 12 个)随机数。将自动选择最后一个数字。

        int[] rn = new int[12];
        
        for(int i=0; i<12; i++) rn[i]=i;   // 0 to 11
        
        Random rNumber = new Random();
        
        int t, z;
        
        for(int i=11; i>0; i--) {
        
            z = rNumber.nextInt(i+1);
        
            t = rn[i];
            rn[i] = rn[z];
            rn[z] = t;
        
        }
        
        System.out.println(Arrays.toString(rn)); 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-10-01
          • 2014-03-22
          • 1970-01-01
          • 1970-01-01
          • 2012-07-19
          • 1970-01-01
          相关资源
          最近更新 更多