I am trying to solve the Josephus problem with an array list. I noticed that even though I remove and index after it is killed it still shows up in my output.
Why does 2 appear again when it should have been removed?
Below is my current output:
There are 7 people in the circle.
1, 2, 3, 4, 5, 6, 7
2
2, 4
2, 4, 1
2, 4, 1, 3
2, 4, 1, 3, 2
2, 4, 1, 3, 2, 0
You should sit in seat 4 if you want to survive!
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(index);
System.out.println(kill_order);
} else if (circle.size()==1){
System.out.println("Execution Order: " + 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!");
}
}
There are two methods
List.remove
: remove(int index) will remove the item at the given index in the list, remove(Object o) will remove the first object equal to o.I think in your code, the
circle.remove(index);
resolves to the first one, but you actually need the second one. See https://docs.oracle.com/javase/8/docs/api/java/util/List.htmlThis should fix that: