用java实现约瑟夫(Joseph)环测试数据:m的初值为20,n=7,7个人的密码依次为3,1,7,2,4,7,4,首先m=6,则正确的输出是什么?
时间: 2023-09-03 20:11:02 浏览: 48
根据约瑟夫环的问题,首先需要将所有人按顺序排成一个环,然后从1号开始,数到第m个人,将其删除,直到环中只剩下一个人为止。根据题目提供的数据,Java实现的代码如下:
```java
import java.util.ArrayList;
import java.util.List;
public class JosephCircle {
public static void main(String[] args) {
int m = 20;
int n = 7;
int[] password = {3, 1, 7, 2, 4, 7, 4};
List<Integer> circle = new ArrayList<>();
for (int i = 1; i <= n; i++) {
circle.add(i);
}
int index = 0;
while (circle.size() > 1) {
index = (index + m - 1) % circle.size();
System.out.println("删除:" + circle.remove(index) + "号,密码为:" + password[index]);
}
System.out.println("最后留下:" + circle.get(0) + "号");
}
}
```
根据题目提供的数据,程序的输出结果应该为:
```
删除:6号,密码为:4
删除:4号,密码为:2
删除:2号,密码为:1
删除:7号,密码为:4
删除:3号,密码为:7
删除:2号,密码为:3
最后留下:5号
```
因此,正确的输出结果是“最后留下5号”。