1. 程式人生 > >C#面試題:一群小孩圍成一個圈的經典演算法

C#面試題:一群小孩圍成一個圈的經典演算法

一群小孩圍成一個圈,從第一個開始報數,報到5的小孩退出圈,繼續,求剩下的最後一個小孩的編號。

程式碼如下:

  1. public static int count = 0;//計數器
  2.         public static int target = 5;//指定編號
  3.         public static void Main (string[] args)
  4.         {
  5.             ArrayList all = new ArrayList ();//集合儲存全部小孩
  6.             ArrayList dela = new ArrayList ();//集合儲存退出圈的小孩
  7.             for (int i = 1; i <= 100; i++) {
  8.                 all.Add (i);//所有小孩新增到all集合中
  9.             }
  10.             while (true) {
  11.                 //如果只剩一個就退出
  12.                 if (all.Count == 1) {
  13.                     break;
  14.                 }
  15.                 foreach (var a in all) {
  16.                     count++;
  17.                     if (count == target) {
  18.                         count = 0;
  19.                         dela.Add (a);//退出圈的小孩新增到dela集合中
  20.                     }
  21.                 }
  22.                 foreach (var a in dela) {
  23.                     all.Remove (a);//退出圈的小孩從all集合中刪除
  24.                 }
  25.                 foreach (var a in all) {
  26.                     Console.WriteLine (a);//最後剩下的小孩
  27.                 }
  28.             }
  29.         }

這是一道C#經典面試題。 大家如果有更好的方法,麻煩分享一下,大家一起進步。