約瑟夫環是一個數學的應用問題:已知n個人(以編號1,2,3...n分別表示)圍坐在一張圓桌周圍。從編號為k的人開始報數,數到m的那個人出列;他的下一個人又從1開始報數,數到m的那個人又出列;依此規律重複下去,直到圓桌周圍的人全部出列。
例如:
n = 9, k = 1, m = 5
【解答】
出局人的順序為5, 1, 7, 4, 3, 6, 9, 2, 8。
using System;using System.Collections.Generic;using System.Text;namespace Jose{ class Program { public int[] Jose(int total, int start, int num) { int i; int j; int k; int[] count; //記錄出隊列的順序 int[] people; //記錄玩家編號 j = 0; k = 0; count = new int[total]; people = new int[total + 1]; for (i = 0; i < total; i++) //給玩家編號 { people[i] = i; } for (i = total; i > 1; i--) { start = (start + num - 1) % i; if (start == 0) start = i; //找到出隊玩家 count[k++] = people[start]; //記錄出隊玩家 for (j = start + 1; j <= i; j++) people[j - 1] = people[j]; //玩家出隊,調整剩餘玩家 } count[k] = people[1]; return count; } static void Main(string[] args) { Program game = new Program(); int[] result = game.Jose(9, 0, 5); foreach (int o in result) { Console.WriteLine("編號為: " + o + " 的玩家出隊"); } Console.ReadKey(); } }}