聽說著名猶太曆史學家 Josephus有過如下的故事:在羅馬人佔領喬塔帕特後,39 個猶太人與Josephus及他的朋友躲到一個洞中,39個猶太人決定寧願死也不要被敵人到,因而決定了一個自殺方式,41我的排成一個圓圈,由第1我的開始報數,每報數到第3人該人就必須自殺,而後再由下一個從新報數,直到全部人都自殺身亡爲止。
然而Josephus 和他的朋友並不想聽從,Josephus要他的朋友先僞裝聽從,他將朋友與本身安排在第16個與第31個位置,因而逃過了這場死亡遊戲。
java
約瑟夫問題可用代數分析來求解,將這個問題擴大好了,假設如今您與m個朋友不幸參與了這個遊戲,您要如何保護您與您的朋友?只要畫兩個圓圈就可讓本身與朋友免於死亡遊戲,這兩個圓圈內圈是排列順序,而外圈是自殺順序,以下圖所示:
數組
使用程式來求解的話,只要將陣列看成環狀來處理就能夠了,在陣列中由計數1開始,每找到三個無資料區就填入一個計數,直而計數達41爲止,而後將陣列由索引1開始列出,就能夠得知每一個位置的自殺順序,這就是約瑟夫排列,41我的而報數3的約琴夫排列以下所示:
spa
14 36 1 38 15 2 24 30 3 16 34 4 25 17 5 40 31 6 18 26 7 37 19 8 35 27 9 20 32 10 41 21 11 28 39 12 22 33 13 29 23
code
由上可知,最後一個自殺的是在第31個位置,而倒數第二個自殺的要排在第16個位置,以前的人都死光了,因此他們也就不知道約琴夫與他的朋友並無遵照遊戲規則了。
索引
C遊戲
#include <stdio.h> #include <stdlib.h> #define N 41 #define M 3 int main(void) { int man[N] = {0}; int count = 1; int i = 0, pos = -1; int alive = 0; while(count <= N) { do { pos = (pos+1) % N; // 環狀處理 if(man[pos] == 0) i++; if(i == M) { // 報數爲3了 i = 0; break; } } while(1); man[pos] = count; count++; } printf("\n約琴夫排列:"); for(i = 0; i < N; i++) printf("%d ", man[i]); printf("\n\n您想要救多少人?"); scanf("%d", &alive); printf("\nL表示這%d人要放的位置:\n", alive); for(i = 0; i < N; i++) { if(man[i] > alive) printf("D"); else printf("L"); if((i+1) % 5 == 0) printf(" "); } printf("\n"); return 0; }
javait
package ss;io
public class Josephus {class
public static int[] arrayOfJosephus(int number, int per) {im
int[] man = new int[number];
//count表明數組中各個位置的人是第幾個自殺的
//報數爲per的倍數時i設爲0,不然i++
for (int count = 1, i = 0, pos = -1; count <= number; count++) {
do {
//造成環狀處理,由於數組角標從零開始,因此pos初始值爲-1
pos = (pos + 1) % number;
if (man[pos] == 0)
i++;
if (i == per) { // 報數爲3了
i = 0;
break;
}
} while (true);
//獲得第count個自殺的人的數組對應位置,並把其數值設置爲count,其他的默認爲0.
man[pos] = count;
}
return man;
}
public static void main(String[] args) {
int[] man = Josephus.arrayOfJosephus(41, 3);
int alive = 2;
System.out.println("約琴夫排列:");
for (int i = 0; i < 41; i++)
System.out.print(man[i] + " ");
System.out.println("\nL表示"+alive+"個存活的人要放的位置:");
for (int i = 0; i < 41; i++) {
if (man[i] <=41-alive)
System.out.print("D");
else
System.out.print("L");
if ((i + 1) % 5 == 0)
System.out.print(" ");
}
System.out.println();
}
}
運行結果:
約琴夫排列:
14 36 1 38 15 2 24 30 3 16 34 4 25 17 5 40 31 6 18 26 7 37 19 8 35 27 9 20 32 10 41 21 11 28 39 12 22 33 13 29 23
L表示2個存活的人要放的位置:
DDDDD DDDDD DDDDD LDDDD DDDDD DDDDD LDDDD DDDDD D