偶尔看到!

来源:互联网 发布:东京工业大学知乎 编辑:程序博客网 时间:2024/04/30 07:41
有n个孩子(编号1,2...n)围成一圈,现在从编号为k的孩子开始报数,当报数到m时,报m的那个孩子出列,然后从报m的那个孩子的下一个孩子重新开始从1报数...
求:孩子们出列的序列。
static void Main(string[] args) { int[] a = new int[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; OutQueue(a, 2, 4); } static void OutQueue(int[] obj, int k, int m) { if (obj == null || obj.Length == 0) return; if (k < 1 || k > obj.Length) { Console.WriteLine("K value is invalid!"); return; } if (m <= 0) { Console.WriteLine("m value is invalid!"); return; } int count = 0; //同m比较,数到m就输出当前位置 int mod = m % obj.Length == 0 ? obj.Length : m % obj.Length; //防止m超过数组长度,取模代替之 int index = k-1; //存放当前的index,为什么要-1?因为数组下标从0开始 int got = 0; while (got < obj.Length - 1) { count = 1; for (int j = 0; j < mod; j++) { if (count == mod) { while (obj[index % obj.Length] == 0) index++; Console.WriteLine("The {0} person is out of queue!", index % obj.Length + 1); got++; obj[index % obj.Length] = 0; } count++; index++; } } for (int i = 0; i < obj.Length; i++) { if (obj[index % obj.Length] != 0) Console.WriteLine("The {0} person is out of queue!", index % obj.Length + 1); index++; } }
原创粉丝点击