約瑟夫環問題: 設有n個人圍坐在圓桌周圍,現從某個位置m(1≤m≤n)上的人開始報數,報數到k的人就站出來。
繼續下一個人,即原來的第k+1個位置上的人,又從1開始報數,再報數到k的人站出來。依此重複下去,直到全部的人都站出來為止
using System;
using System.Collections.Generic;
using System.Text;
namespace ExJose
{
class ClassJose {
//從第start人開始計數,以alter為單位迴圈記數出列,總人數為total
public int[] Jose(int total, int start,int alter)
{
int j, k = 0;
//count數組儲存按出列順序的資料,以當結果返回
int[] count = new int[total + 1];
//s數組儲存初始資料
int[] s = new int[total + 1];
//對數組s賦初值,第一個人序號為0,第二人為1,依此下去
for (int i = 0; i < total; i++)
{
s[i] = i;
}
//按出列次序依次存於數組count中
for (int i = total; i >= 2; i--)
{
start = (start + alter - 1) % i;
if (start == 0)
start = i;
count[k] = s[start];
k++;
for (j = start + 1; j <= i; j++)
s[j - 1] = s[j];
}
count[k] = s[1];
//結果返回
return count;
}
static void Main(string[] args)
{
ClassJose e=new ClassJose ();
int[] a = e.Jose(10,3,4);
for (int i = 0; i < a.Length; i++)
{
Console.WriteLine(a[i].ToString ());
}
}
}
}