从第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;
}
其中,total为总人数,n为第N个位置,m为每隔M人一个出列。
接下来,我们要使用一个循环结构来实现算法。由于我们需要从第n个位置开始,因此循环的初始值应该是(n-1)。而且,由于每隔m人一个出列,因此循环的步长应该是m。
public static void OutList(int total, int n, int m)
{
int[] array = new int[total];
for (int i = 0; i < total; i++)
array[i] = i + 1;
Console.WriteLine($"总人数:{total},第{m}个位置,每隔{m}人一个出列。");
int index = n - 1;
for (int i = 0; i < total - n + 1; i++)
{
Console.Write($"{array[index]} ");
array[index] = -1;
int count = 0;
while (count < m)
{
index = (index + 1) % total;
if (array[index] != -1)
count++;
}
}
Console.ReadLine();
}
经过这样的操作,我们就可以得到想要的结果。
除此之外,我们还可以添加更多的调试信息来帮助我们更好的了解代码的运行情况。例如,在输出时,我们可以添加每个人的位置信息,这样可以更好的了解每个人在最终的出队顺序中的位置。