1. 程式人生 > 其它 >Java 實現約瑟夫環問題

Java 實現約瑟夫環問題

技術標籤:java

1.迴圈報數遊戲,有n個人,從1到k報數,報道k 的退出遊戲,得出最後獲勝人的編號,編號從0開始。
思路:
一.建立大小為 n 的boolean型別的陣列,並把所有元素初始化為true;
二.使用while迴圈,迴圈的條件為獲勝的人數大於1。從0下標位置開始迴圈判斷,這裡分為三種情況:
1.index位置的值為true ,且count ==k ,這種情況是找到了退出遊戲的人。則把這個位置的值改為false;活著的人數減一,計數繼續從1開始計數。
2.index位置的值為true,且count != k;這種情況是還沒有找到k位置的人,則繼續報數,index++,count++;

3.index位置的值為false ,這種情況是index位置的人已經退出遊戲,則count不需要加加,index++就行。
三.找到數組裡唯一一個值是true的下標並返回;
下面是程式碼實現:

public static int CyclicGame(int n, int key) {
        //建立一個大小為 n 的boolean型別陣列,所有元素初始化為true;
        boolean[] array = new boolean[n];
        for (int i=0; i<n; i++) {
            array[i]=true;
        }
//count 報數,index 陣列下標,peopleLeft 活著的人數。 int count = 1; int index = 0; int peopleLeft = n; //只要活著的人大於1就繼續迴圈。 while (peopleLeft >= 2) { //如果index下標的值為true且滿足報數到k。則把這個下標的值改為flase; //則活著的人peopleLeft--,報數繼續從1 開始報數 count =1; if
(array[index] == true && count == key) { array[index] = false; peopleLeft --; count = 1; } else if (array[index] && count != key) { //如果index下標的值為true 且count 的值不為k。則count++;index++; count ++; index = (++ index) % n; } else { //如果index下標的值為flase,則只需index++; index = (++ index) % n; //[0, n-1] } } //找活著的那個; for (int i=0; i<n; ++i) { if(array[i]) { return i; } } return -1; } public static void main(String[] args) { System.out.println(CyclicGame(4, 3)); }

這裡只是個人的學習總結。有什麼問題歡迎提意見。