1. 程式人生 > 實用技巧 >ArrayList實現約瑟夫環

ArrayList實現約瑟夫環

ArrayList實現約瑟夫環

​ 約瑟夫遊戲的大意:30個遊客同乘一條船,因為嚴重超載, 加上風浪大作,危險萬分。因此船長告訴乘客,只有將全船 一半的旅客投入海中,其餘人才能倖免於難。無奈,大家只得同意這種辦法,並議定30 個人圍成一圈,由第一個人數起,依次報數,數到第9人,便把他投入大海中,然後再從 他的下一個人數起,數到第9人,再將他投入大海中,如此迴圈地進行,直到剩下 15 個遊客為止。問:哪些位置是將被扔下大海的位置?

將 30 改為一個任意輸入的正整數 n,而報數 上限(原為9)也為一個任選的正整數k

程式碼實現

package com.ks.ysfh;
/**
 *  
 * @author 柯神_
 * @date 2020-12-25 19:53:49 
 * @Description 約瑟夫環
*/
import java.util.ArrayList;

public class YSFH {
  public static void main(String[] args) {
    sF(10, 10);
  }


  public static void sF(int total, int count) {
    ArrayList<Integer> list = new ArrayList();
    int rmIndex = 0;

    //1.新增到集合
    for (int i = 0; i < total; i++) {
      list.add(i);
    }

    while (list.size() > 3) {
      rmIndex = rmIndex + count - 1;

      if (rmIndex > list.size() - 1) {
        rmIndex = rmIndex % (list.size());   //當前索引超過了陣列的最大索引時,對集合大小求餘得到需要刪除的新索引
      }

      System.out.println(list.get(rmIndex));
      int c = list.remove(rmIndex);
      System.out.println(list);

      //也可以通過if語句來得到最後一次刪除的資料
      if (list.size() == 3) {
        System.out.println("最後一次刪除的資料:" + c);
        return;
      }
    }
  }
}

結果演示