您的位置:首页 > 编程语言 > C#

C# 约瑟夫环算法

2016-02-18 15:02 686 查看
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 约瑟夫环算法
{
class Program
{
const int Num = 41;
const int KillNum = 3;

static void Main(string[] args)
{
Console.WriteLine("41个人");
Console.WriteLine("从0开始计算,每过3人就自杀");

Josephous(3);

Console.ReadLine();
}

/// <param name="alive">需要存留的人数</param>
static void Josephous(int alive)
{
int[] man = new int[Num];           //有41个人
int count = 0;                      //死亡人数
int i = 0;
int pos = 0;                        //当前坐标

while ((Num - count) >= alive)
{
if (man[pos] == 0)
{
i++;                  //如果当前位置有人,记数一个
}

//如果当前是活人,并且计数字=3,就杀掉这个人
if (i == KillNum && man[pos] != 1)
{
i = 0;
man[pos] = 1;
count++;
}
pos = (pos + 1) % Num;      //坐标开始游走
}

//输出现在存活的人
for (int j = 0; j < man.Length; j++)
{
if (man[j] == 0)
{
Console.WriteLine("数组位置: "+ j +"的人可以存活");
}
}

}

}
}


 



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: