如果(某事)重新执行for循环

时间:2018-02-15 01:05:57

标签: java

这个非常简单和基本,但由于某种原因,我无法做到正确。所以我正在创建一个for循环并在for循环中生成随机数,但我希望通过在这些数字出现时重做for循环来消除一些数字。我应该怎么做,我的错误是什么。提前谢谢。

我是怎么做到的:

int[] array= new int[6];
for(int i=0;i<array.length;i++){
   Random rand = new Random();
   int  n = rand.nextInt(50) + 1;
   if(n==5 || n==9 || n==13){
      i--;
      return;
   }
   array[i]=n;
}

6 个答案:

答案 0 :(得分:3)

我认为最干净的方法是让一个内循环循环,直到你得到一个可接受的数字。这样,如果需要,内部循环可以稍后被考虑到函数中。我还将随机数生成器初始化移出循环,因为我认为这是预期的。

Random rand = new Random();
for (int i = 0; i < array.length; ++i) {
  int n = rand.nextInt(50) + 1;
  while (n == 5 || n == 9 || n == 13) {
    n = rand.nextInt(50) + 1;
  }
  array[i] = n;
}

答案 1 :(得分:3)

这是一篇有趣的帖子。只想插入并分享我的第一直觉。也许这不是传统的。

如果你遇到5,9,13,那么没有理由再次滚动。这种方法可以是确定性的

算法:

  1. 在1-47之间选择一个 R 的数字(数字1-4,6-8,10-12,14-50都是同等可能的)
  2. 如果R == 5则R = 48
  3. 否则如果R == 9则R = 49
  4. 否则如果R == 13则R = 50
  5. 这可以轻松地转换为传递一组不需要的数字的功能。

答案 2 :(得分:1)

看起来你可以使用 while-loop

int[] array= new int[6];
int i = 0;
while(i<array.length){
   Random rand = new Random();
   int  n = rand.nextInt(50) + 1;
   if(n!=5 && n!=9 && n!=13){
       array[i++] = n;  
   }
}

答案 3 :(得分:1)

您可以执行的操作是生成[1, .., 50]中的数字列表,并从该列表中删除您不想要的数字:[5, 9, 13]。像这样:

List<Integer> unwatedNums = Arrays.asList(5, 9, 13);
List<Integer> list = IntStream.rangeClosed(1, 50).boxed().collect(Collectors.toList());
list.removeAll(unwatedNums);

现在你可以安全地从该列表中获取一个随机元素,而不会在某些情况下不必要地获取一个新的随机数:

int[] array= new int[6];
for(int i=0;i<array.length;i++){
    array[i]=list.get((new Random()).nextInt(list.size()));
}

答案 4 :(得分:0)

最干净的方法是确保不生成您不想要的数字 - 您可以根据要排除的数量来调整范围。

此功能会为您提供lowRangehighRange(包括两端)的随机数,不包含without中指定的任何数字:

public static int randomWithout(Random rand, int lowRange, int highRange, int... without) {
    int range = highRange - lowRange + 1 - without.length;
    int result = rand.nextInt(range) + lowRange;
    for (int i = 0; i < without.length; i++) {
        if (result >= without[i]) {
            result++;
        }
    }
    return result;
}

然后您可以使用此功能:

int[] array = new int[6];
Random rand = new Random();
for (int i = 0; i < array.length; ++i) {
    array[i] = randomWithout(rand, 1, 50, 5, 9, 13);
}

最大的优势是确定性的运行时间 - 使用while循环,而你得到一个你不想要的数字理论上可以永远运行。

答案 5 :(得分:0)

答案很棒,如果你和我有同样的问题,我建议你不管看看答案,但我正在寻找的答案如下:

int[] array= new int[6];
for(int i=0;i<array.length;i++){
   Random rand = new Random();
   int  n = rand.nextInt(50) + 1;
   if(n==5 || n==9 || n==13){
      i--;
      continue; // this has solved my problem
   }
 array[i]=n;
}