常用演算法(C#): 約瑟夫環問題

來源:互聯網
上載者:User

約瑟夫環問題: 設有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 ());
            }
        }
    }
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.