I am trying to solve the Josephus problem with an ArrayList and for loops. I have created an infinite for loop within my circle.size for loop but I cant deduce which part of my code is causing it to happen.
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!");
}
}
I think that the problem is related to this line of code
circle.remove((Integer)index);
if you replace with
circle.remove(index)
the programs end without any infinite loop.If you call the method
circle.remove((Integer) index)
it search an element inside the array with that value, the methodcircle.remove(index)
it remove the element at the specified index.See the javadoc for additional details remove(int index) remove(Object o)