约瑟夫环问题(100围坐一圈报数,报3出圈)
100个人编号1-100,围坐一圈,从1号开始进行1,2,3报数,谁报数为3,就离开圈子,剩下的人继续报1,2,3,报数为3的出圈。。
public static void CalNum(int numCount)
{
List<int> array = new List<int>(numCount);
for (int i = 1; i <= numCount; i++)
{
array.Add(i);
}
var circleList = new CircleArrayList<int>(array);
int num = 0;
while (true)
{
if (circleList.Lengh == 1)
{
break;
}
num += 1;
if (num == 3)
{
circleList.Remove();
num = 0;
}
else
{
circleList.MoveNext();
}
}
Console.WriteLine(circleList.Current);
}
public class CircleArrayList<T> : IEnumerator<T>
{
private List<T> interal;
private int index = 0;
public CircleArrayList(List<T> list)
{
this.interal = list;
}
public T Current
{
get { return interal[index]; }
}
public void Dispose()
{
return;
}
object IEnumerator.Current
{
get { return interal[index]; }
}
public bool MoveNext()
{
index += 1;
if (index == interal.Count)
index = 0;
return true;
}
public void Reset()
{
index = 0;
}
public void Remove()
{
interal.RemoveAt(index);
if (index == interal.Count)
index = 0;
}
public int Lengh
{
get
{
return interal.Count;
}
}
}
CalNum(600);