约瑟夫环问题:已知n个人(以编号1,2,3...n分别表示)围坐在一张圆桌周围。从编号为k的人开始报数,数到m的那个人出列;他的下一个人又从1开始报数,数到m的那个人又出列;依此规律重复下去,直到圆桌周围的人全部出列。例如:n = 9, k = 1, m = 5
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SY2
{
class Program
{
static void Main(string[] args)
{
int[] arr = new int[9];//一共9人
for (int i = 0; i < arr.Length; i++)//编号1~9
{
arr[i] = i+1;
}
int interval = 5;//从1开始数,到第6个人就杀
int remainder = arr.Length;//剩余人数
int tally = interval;
int index = 1;
while (remainder > 1)
{
if (arr[index] != -1)
{
tally--;
if (tally == 0)
{
arr[index] = -1;
remainder--;
tally = interval;
if (index == 0)
Console.WriteLine("kill:No" + arr.Length + " remain" + remainder);
else
Console.WriteLine("kill:No" + index + " remain:" + remainder);
}
}
index++;
if (index == arr.Length)
{
index = 0;
}
}
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] != -1)
{
if (i == 0)
Console.WriteLine("the survivor is:No" + arr.Length);
else
Console.WriteLine("the survivor is:No" + i);
Console.ReadLine();
return;
}
}
}
}
}