A solution to the three different ways to solve the Josephus problem
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
for (int i = 1; i < 21; i++) {
System.out.println(josephus1(i)); // print out the first 20 josephi (note the pattern)
}
}
public static void populateList(ArrayList<Integer> alist, int n) {
for (int i = 1; i <= n; i++) {
alist.add(i);
}
}
public static int josephus1(int n) {
ArrayList<Integer> knights = new ArrayList<Integer>();
populateList(knights, n);
System.out.println(knights);
int index = 1; // skip over knight at position 0 to start
while (knights.size() > 1) { // more than one knight remains, so must kill another
knights.remove(index);
index = (index + 1) % knights.size(); // Go back to start of list of size exceeded
}
return knights.get(0);
}
public static int josephus2(int n) { // Example: 91
String str = Integer.toBinaryString(n); // 91 decimal = 1011011 binary
str = str.substring(1) + str.charAt(0); // circularLeftShift(1011011) --> 0110111
return Integer.parseInt(str,2); // 110111 binary = 55 decimal
}
public static int josephus3(int n) { // Example: 91
int expt = (int) Math.floor(Math.log(n)/Math.log(2)); // 6 = log2(64) < log2(91) < log2(128) = 7
int divisor = (int) Math.pow(2, expt); // 2^6 = 64
int remainder = n % divisor; // 91/64 = 1 R 27
return 2 * remainder + 1; // 2 * 27 + 1 = 55 (the survivor)
}
}