問題描述:
設有n個人圍坐一圈,現以某個人開始報數,數到m的人出列,接著從出列的下一個人開始重新報數,數到m的人又出列,如此下去,直到所有人都出列為止.按出列順序輸出.
//******************************
//描述:約瑟夫環問題
//類名:Josephas
//作者:洪曉軍
//時間:2004-12-27
//******************************
1 public class Josephas
2 {
3 //從第start人開始計數,以alter為單位迴圈記數出列,總人數為total
4 public int [ ] Jose(int total, int alter, int start)
5 {
6 int i, j, k = 0;
7
8 //count數組儲存按出列順序的資料,以當結果返回
9 int[] count = new int [ total+1];
10
11 //s數組儲存初始資料
12 int[] s = new int [ total+1];
13
14 //對數組s賦初值,第一個人序號為0,第二人為1,依此下去
15 for (i = 0; i <total; i++)
16 {
17 s[i] = i;
18 }
19
20 //按出列次序依次存於數組count中
21 for (i = total; i >= 2; i--)
22 {
23 start = (start + alter - 1) % i;
24 if (start == 0)
25 start = i;
26 count[k] = s[start];
27 k++;
28 for (j = start + 1; j <= i; j++)
29 s[j - 1] = s[j];
30 }
31
32 count[k]=s[1];
33
34 //結果返回
35 return count;
36 }
37 }
以上程式在Microsoft Visual Studio .NET 2003 和Visual C# 2005 Express Edition Beta1中均調試通過.