public class Josephus {
private int total;
private int num;
private int[] array;
public Josephus(int total, int num) {
this.total = total;
this.num = num;
array = new int[total];
for (int i = 0; i < total; i++) {
array[i] = i + 1;
}
}
public static void main(String[] args) {
Josephus josephus = new Josephus(20, 3);
josephus.josephus();
}
public void josephus() {
int i, j;
if (this.getTotal() <= 0 || this.getNum() <= 0) //處理引數值不正確的情況
{
System.out.println("Paramter must bigger than zero!");
return;
}
int k = 1; //標識處理第k個離開的人
i = -1; //陣列下標,下一個為0,即第一個人
while (true) //k等於n表示只剩下一個人了
{
for (j = 0; j < this.getNum();) //在圈中數m個人
{
i = (i + 1) % this.getTotal();
if (this.getArray()[i] > 0) {
j++; //a[i] >0表示第i個人還沒有離開
}
}
if (k == this.getTotal()) {
break;
}
System.out.println("No." + this.getArray()[i] + " is out!");
this.getArray()[i] = -1; //表示該人離開
k++;
}
System.out.println("No." + this.getArray()[i] + " is the winner!");
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public int[] getArray() {
return array;
}
public void setArray(int[] array) {
this.array = array;
}
}