[c#演算法和資料結構]約瑟夫環問題

來源:互聯網
上載者:User

問題描述:
       設有n個人圍坐一圈,現以某個人開始報數,數到m的人出列,接著從出列的下一個人開始重新報數,數到m的人又出列,如此下去,直到所有人都出列為止.按出列順序輸出.
 
     //******************************    
     //描述:約瑟夫環問題
     //類名:Josephas
     //作者:洪曉軍
     //時間:2004-12-27
     //******************************   

 1    public class Josephas 
 2    { 
 3        //從第start人開始計數,以alter為單位迴圈記數出列,總人數為total 
 4        public int [ ] Jose(int total, int alter, int start)     
 5        {          
 6            int i, j, k = 0; 
 7
 8             //count數組儲存按出列順序的資料,以當結果返回 
 9            int[] count = new int [ total+1];    
10
11            //s數組儲存初始資料 
12            int[] s = new int [ total+1];     
13
14             //對數組s賦初值,第一個人序號為0,第二人為1,依此下去
15            for (i = 0; i <total; i++)     
16            { 
17                s[i] = i; 
18            } 
19
20            //按出列次序依次存於數組count中 
21            for (i = total; i >= 2; i--)      
22            { 
23                start = (start + alter - 1) % i; 
24                if (start == 0) 
25                    start = i; 
26                count[k] = s[start]; 
27                k++; 
28                for (j = start + 1; j <= i; j++) 
29                    s[j - 1] = s[j]; 
30            }  
31               
32            count[k]=s[1]; 
33
34            //結果返回 
35            return count;     
36        } 
37    } 


 以上程式在Microsoft Visual Studio .NET 2003 和Visual C# 2005 Express Edition Beta1中均調試通過.
       

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.