题目
主类
java
public static List<Prisoner> prisoners = new ArrayList<Prisoner>();
public static List<Prisoner> remainPrisoners = new ArrayList<Prisoner>();
public static Prisoner lastPrisoner = null;
java
public static void main(String[] args) {
Random random = new Random();
// 循环100次 生成100个囚犯
for (int i = 0; i < 100; i++) {
// 生成随机数
Long code = (long) random.nextInt(200) + 1;
if (existCode(code)) {
i--;
continue;
}
Prisoner prisoner = new Prisoner(code,(long) i + 1);
prisoners.add(prisoner);
}
System.out.println("囚犯初始站位:") ;
prisoners.forEach(System.out::println);
// 深拷贝
remainPrisoners = new ArrayList<>(prisoners);
// 开始枪毙囚犯
while (remainPrisoners.size() > 1) {
killPrisoner();
}
lastPrisoner = remainPrisoners.get(0);
System.out.println("最后一个囚犯编号:" + lastPrisoner.getCode());
System.out.println("最后一个囚犯站位:" + lastPrisoner.getFirstPlace() );
}
java
public static boolean existCode(Long code) {
// 判断囚犯编号是否存在 使用stream流
return prisoners.stream().anyMatch(prisoner -> code.equals(prisoner.getCode()));
}
java
// 枪毙囚犯(枪毙奇数位置的囚犯)
public static void killPrisoner() {
for (int i = remainPrisoners.size(); i > 0 ; i--) {
if (i % 2 != 0) {
System.out.println(i);
remainPrisoners.remove(i-1);
}
}
System.out.println("剩余囚犯:");
remainPrisoners.forEach(System.out::println);
}
囚犯类
java
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Prisoner {
private Long code;
private Long firstPlace;
}