常用算法(C#): 约瑟夫环问题

约瑟夫环问题: 设有n个人围坐在圆桌周围,现从某个位置m(1≤m≤n)上的人开始报数,报数到k的人就站出来。

继续下一个人,即原来的第k+1个位置上的人,又从1开始报数,再报数到k的人站出来。依此重复下去,直到全部的人都站出来为止

 

using System;
using System.Collections.Generic;
using System.Text;

namespace ExJose

{
    class ClassJose    {
        //从第start人开始计数,以alter为单位循环记数出列,总人数为total
        public int[] Jose(int total, int start,int alter)
        {
            int j, k = 0;
            //count数组存储按出列顺序的数据,以当结果返回
            int[] count = new int[total + 1];
            //s数组存储初始数据
            int[] s = new int[total + 1];
            //对数组s赋初值,第一个人序号为0,第二人为1,依此下去
            for (int i = 0; i < total; i++)
            {
                s[i] = i;
            }
            //按出列次序依次存于数组count中
            for (int i = total; i >= 2; i–)
            {
                start = (start + alter – 1) % i;
                if (start == 0)
                    start = i;
                count[k] = s[start];
                k++;
                for (j = start + 1; j <= i; j++)
                    s[j – 1] = s[j];
            }
            count[k] = s[1];
            //结果返回
            return count;
        }

        static void Main(string[] args)
        {
            ClassJose    e=new ClassJose     ();
            int[] a = e.Jose(10,3,4);
            for (int i = 0; i < a.Length; i++)
            {
                Console.WriteLine(a[i].ToString ());
            }
        }
    }
}

    原文作者:约瑟夫环问题
    原文地址: https://www.cnblogs.com/ziyiFly/archive/2008/09/10/1288105.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞