? 约瑟夫游戏的大意: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;
}
}
}
}
原文:https://www.cnblogs.com/qqkkOvO/p/14190581.html