C# 约瑟夫环算法

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 +"的人可以存活");
                }
            }

        }

    }
}

 

《C# 约瑟夫环算法》

    原文作者:盘子脸
    原文地址: https://www.cnblogs.com/plateFace/p/5198236.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞