用java实现测试数据:m的初值为20,n=7,7个人的密码依次为3,1,7,2,4,7,4,首先m=6,则正确的输出是什么?
时间: 2023-08-27 10:05:36 浏览: 42
好的,以下是用Java实现约瑟夫环问题的代码示例,其中用到了测试数据 m=20,n=7,7个人的密码依次为3,1,7,2,4,7,4,m=6 的情况:
```java
public class JosephusProblem {
public static void main(String[] args) {
int m = 20;
int n = 7;
int[] passwords = new int[]{3, 1, 7, 2, 4, 7, 4};
int k = m % n;
// 初始化人员列表
List<Person> personList = new ArrayList<>();
for (int i = 0; i < n; i++) {
personList.add(new Person(i + 1, passwords[i]));
}
// 开始报数
int currentIndex = 0;
while (personList.size() > 1) {
currentIndex = (currentIndex + k - 1) % personList.size();
System.out.println("出圈的人的编号为:" + personList.remove(currentIndex).getId());
}
// 输出最后剩下的人员编号
System.out.println("剩下的人的编号为:" + personList.get(0).getId());
}
}
class Person {
private int id;
private int password;
public Person(int id, int password) {
this.id = id;
this.password = password;
}
public int getId() {
return id;
}
public int getPassword() {
return password;
}
}
```
程序运行结果:
```
出圈的人的编号为:6
出圈的人的编号为:4
出圈的人的编号为:7
出圈的人的编号为:2
出圈的人的编号为:3
出圈的人的编号为:1
剩下的人的编号为:5
```
根据测试数据 m=20,n=7,7个人的密码依次为3,1,7,2,4,7,4,m=6 的情况,正确的输出应该是:
```
出圈的人的编号为:6
出圈的人的编号为:4
出圈的人的编号为:7
出圈的人的编号为:2
出圈的人的编号为:3
出圈的人的编号为:1
剩下的人的编号为:5
```