日期:2014-05-20 浏览次数:20956 次
package zeng.javatest;
import java.util.Scanner;
public class Josephus {
private int getCrimerNum() {
int crimerNum = 0;
System.out.println("输入犯人的数量:");
Scanner sc = new Scanner(System.in);
crimerNum = sc.nextInt();
sc.close();
return crimerNum;
}
private int getStartNum() {
int startNum = 0;
System.out.println("输入从几号开始计数:");
Scanner sc = new Scanner(System.in);
startNum = sc.nextInt();
sc.close();
return startNum;
}
private int getCount() {
int counter = 0;
System.out.println("输入一个count:");
Scanner sc = new Scanner(System.in);
counter = sc.nextInt();
sc.close();
return counter;
}
private int[] init(int n) {
int a[] = new int[n];
for (int i = 0; i < a.length; i++) {
a[i] = i + 1;
}
return a;
}
private boolean countCrimerNum(int a[]) {
int count = 0;
for (int i = 0; i < a.length; i++) {
if(a[i] == 0){
count ++;
}
}
if (count < (a.length - 1)) {
return true;
}
else return false;
}
private int[] killCrimer(int a[], int s, int d) {
int index = 0;
int n = a.length;
index = (s+d)%n;
a[index] = 0;
System.out.println("第"+(index + 1)+"个犯人被处刑");
return a;
}
public static void main(String[] args) {
int n = 0, s = 0, d = 0;
Josephus jj = new Josephus();
n = jj.getCrimerNum();
s = jj.getStartNum();
d = jj.getCount();
int crimer[] = new int[n];
crimer = jj.init(n);
while(jj.countCrimerNum(crimer)){
crimer = jj.killCrimer(crimer, s, d);
s = (s + d)%n;
}
}
}
import java.util.Scanner;
public class Josephus {
static Scanner sc = null;