题目
主类
public static List < Prisoner > prisoners = new ArrayList < Prisoner > ( ) ;
public static List < Prisoner > remainPrisoners = new ArrayList < Prisoner > ( ) ;
public static Prisoner lastPrisoner = null ;
public static void main ( String [ ] args) {
Random random = new Random ( ) ;
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 ( ) ) ;
}
public static boolean existCode ( Long code) {
return prisoners. stream ( ) . anyMatch ( prisoner -> code. equals ( prisoner. getCode ( ) ) ) ;
}
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 ) ;
}
囚犯类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Prisoner {
private Long code;
private Long firstPlace;
}