zoukankan      html  css  js  c++  java
  • 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 +"的人可以存活");
                    }
                }
    
            }
    
        }
    }

    image

  • 相关阅读:
    7-4
    7-3
    第五章例5-2
    第五章例5-1
    第四章例4-12
    第四章例4-11
    第四章例4-10
    第四章例4-9
    第四章例4-8
    第四章例4-7
  • 原文地址:https://www.cnblogs.com/plateFace/p/5198236.html
Copyright © 2011-2022 走看看