void setup() { println("Survivor: " + execute(41, 3)); println("Survivors: " + executeAllButM(41, 3, 3)); } int execute(int n, int k) { int killIdx = 0; IntList prisoners = new IntList(n); for (int i = 0; i < n; i++) { prisoners.append(i); } println("Prisoners executed in order:"); while (prisoners.size() > 1) { killIdx = (killIdx + k - 1) % prisoners.size(); print(prisoners.get(killIdx) + " "); prisoners.remove(killIdx); } println(); return prisoners.get(0); } IntList executeAllButM(int n, int k, int m) { int killIdx = 0; IntList prisoners = new IntList(n); for (int i = 0; i < n; i++) { prisoners.append(i); } println("Prisoners executed in order:"); while (prisoners.size() > m) { killIdx = (killIdx + k - 1) % prisoners.size(); print(prisoners.get(killIdx) + " "); prisoners.remove(killIdx); } println(); return prisoners; }