【问题标题】:I have an infinite for loop but I cant find which part of my code is causing it我有一个无限的 for 循环,但我找不到我的代码的哪一部分导致它
【发布时间】:2021-05-12 11:31:03
【问题描述】:

我正在尝试使用 ArrayList 和 for 循环来解决 Josephus 问题。我在我的 circle.size for 循环中创建了一个无限 for 循环,但我无法推断我的代码的哪一部分导致它发生。

public class project1 {
  public static int Josephus (int n, int k){                                     
    ArrayList<Integer> circle = new ArrayList<Integer>();                       
    for (int p = 1; p <= n; p++) {                                              
      circle.add(p);                                                            
    }
    System.out.println("There are " + n + " people in the circle.");            
    System.out.println(circle);                                                 

    ArrayList<Integer> kill_order = new ArrayList<Integer>();                   
    for (int index=1; circle.size()!=1; index++){                               
      if (circle.size() > 1){                                                   
        index = (index + k - 1) % circle.size();                                
        kill_order.add(index);                                                  
        circle.remove((Integer)index);
        System.out.println(kill_order);
      } else if (circle.size()==1){
        System.out.println("Execution Order: " + kill_order + " ");
        System.out.println(kill_order);
        index = 1;
      }
    }
    return circle.get(0);
  }

  public static void main(String[] args) {
    System.out.println("You should sit in seat " + Josephus(7, 2) + " if you want to survive!");
  }
}

【问题讨论】:

  • 如果是一个空圆圈,或者当 size == 1 时就会出现问题。调试会有所帮助。
  • 欢迎来到 StackOverflow。 doscio 为您提供了正确的答案。我强烈建议学习使用调试器。这样您就可以单步执行您的代码,并在您通过 for 循环时查看变量是如何变化的。

标签: java for-loop arraylist infinite-loop josephus


【解决方案1】:

我认为问题与 circle.remove((Integer)index);这行代码有关

如果你用circle.remove(index) 替换程序结束,没有任何无限循环。

如果调用circle.remove((Integer) index) 方法,它会在数组中搜索具有该值的元素,circle.remove(index) 方法会删除指定索引处的元素。

有关更多详细信息,请参阅 javadoc remove(int index) remove(Object o)

【讨论】:

  • 你第二句话的意思是写circle.remove(index)吗?
  • @dave 是的,已修复 :)
  • @doscio 我最初有 circle.remove(index) 但如果您查看我之前的问题之一stackoverflow.com/questions/66105185/…,则索引不会被删除。
【解决方案2】:

主循环的每次下一次迭代看起来像:

index at the beginning of the loop index after assign new value circle array
1 2 1, 3, 4, 5, 6, 7
3 4 1, 3, 5, 6, 7
5 1 3, 5, 6, 7
2 3 5, 6, 7
4 2 5, 6, 7 - it cannot remove value 2 and array is not size 1
3 1 5, 6, 7
2 0 5, 6, 7
1 2 5, 6, 7
3 1 5, 6, 7 - cycle starts to repeat

所以可能您的算法是错误的,或者您应该删除索引处的元素,而不是按值 (circle.remove(index)) - 而不将其转换为 Integer

【讨论】:

    猜你喜欢
    • 2019-04-22
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 2021-09-17
    • 1970-01-01
    • 2020-12-17
    • 1970-01-01
    • 2022-06-14
    相关资源
    最近更新 更多