用java編寫的程序解決Josephus問題.
package array;
import javax.swing.JOptionPane;
public class Josephus{
/**
Josephus問題
*/
public static void main(String[] args) {
//輸入
String bound = JOptionPane.showInputDialog(null, "輸入孩子總數:",
"輸入", JOptionPane.QUESTION_MESSAGE);
int N = Integer.parseInt(bound);
String message = "輸入m的大小:(0-- ";
message += N + ")";
String m = JOptionPane.showInputDialog(null, message,
"輸入", JOptionPane.QUESTION_MESSAGE);
int P = Integer.parseInt(m);
long time1 = System.currentTimeMillis(); //起始時間
//初始化
int []boy = new int[N];
for(int i=0;i<N;i++)
boy[i] = 1;
//處理
int result = find(boy,P,N);
System.out.println("/n有 " +N+ " 個孩子/n這裏基數m是:" +P);
long time2 = System.currentTimeMillis();
long runtime = time2 - time1;
System.out.println("運行時間是: " +runtime+ "毫秒。");
//輸出
String str = "最後一個孩子下標是:" + result;
JOptionPane.showMessageDialog(null, str,
" 結 果 ", JOptionPane.INFORMATION_MESSAGE);
}
static int find(int[] boy, int p, int n) {
boolean flag = true;
int count = 0;
int i = 0,k = 0;
k = n;
int result = 0;
//flag爲false時退出
while(flag){
if(i == n){
i = 0;
continue;
}
if(boy[i] == -1) {
i++;
continue;
}
else
{
count++;
//循環到第p個孩子做標記,同時count清零
if(count == p){
boy[i] = -1;
count = 0;
k--;
System.out.println(" "+i);
}
if(k == 0)
{
result = i;
System.out.println(" 處理完畢:/n最後一個孩子下標是: "+i+" .");
break;
}
}
//數組下標前移
i++;
}
return result;
}
}