我正在尝试使用 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!");
}
}