日期:2014-05-17 浏览次数:20775 次
//用数组模拟约瑟夫环 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication3 { class Program { /// <summary> /// 返回约瑟夫环出列顺序的数组 /// </summary> /// <param name="total">初始全部人数</param> /// <param name="begin">开始编号</param> /// <param name="dequeue">每多少个出列一个</param> /// <returns></returns> static int[] Josephus(int total, int begin, int dequeue) { int count =0,j;//count要输出的数组的下标 int[] iCounts = new int[total];//结果数组 int[] preCounts = new int[total];//初始数组 for (int i = 0; i < total; i++)//预处理初始数组 { preCounts[i] = i; } for (int i = total-1; i >= 2;i-- ) { begin = (begin + dequeue - 1) % i;//每次应该出列的编号 if (begin == 0) { begin = i; } iCounts[count] = preCounts[begin];//将要出列的编号存入结果数组 count++; for (j = begin+1; j <= i; j++) { preCounts[j - 1] = preCounts[j];//一个人出列后,它后面往前移 } } iCounts[count] = preCounts[1];//最后一个出列的 return iCounts;//返回结果数组 } /// <summary> /// 主函数 /// </summary> /// <param name="args"></param> static void Main(string[] args) { int[] JosArray = Josephus(8,5,2);//共有8个人,从第5个开始,数到2的那个人出列 for (int i = 0; i < JosArray.Length - 1; i++) { Console.Write(JosArray[i] + " ");//输出出列顺序 } Console.ReadLine(); } } }