急求用java解决约瑟夫环的编程(接图片“显示“出环者”次序并给出最终的赦免者”)
发布网友
发布时间:2022-07-15 03:15
我来回答
共1个回答
热心网友
时间:2023-11-18 07:31
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class demo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入总人数:");
int totalNum = scanner.nextInt();
System.out.print("请输入报数的大小:");
int cycleNum = scanner.nextInt();
System.out.print("请输入第几个报数:");
int cur = scanner.nextInt();
yuesefu(totalNum, cycleNum ,cur);
scanner.close();
}
public static void yuesefu(int totalNum, int countNum,int cur) {
// 初始化人数
List<Integer> start = new ArrayList<Integer>();
for (int i = 1; i <= totalNum; i++) {
start.add(i);
}
//从第K个开始计数
int k = cur-1;
while (start.size() >0) {
k = k + countNum;
//第m人的索引位置
k = k % (start.size()) - 1;
// 判断是否到队尾
if (k < 0) {
System.out.println(start.get(start.size()-1));
start.remove(start.size() - 1);
k = 0;
} else {
System.out.println(start.get(k));
start.remove(k);
}
}
}
}