package com.itheima.d1;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class JianYu {
public static List<People> peoples = new ArrayList<>();
public static void main(String[] args) {
Random r = new Random();
for (int i = 1; i <= 100; i++) {
while (true) {
int code = r.nextInt(200) + 1;
if (isCanUse(code)) {
People p = new People(code, i);
peoples.add(p);
break;
}
}
}
System.out.println("囚犯站位" + peoples);
//保留偶数位,等于击毙奇数位
while (peoples.size() > 1){
List<People> tempPeoples = new ArrayList<>();
for (int i = 1; i < peoples.size(); i += 2) {
People p = peoples.get(i);
tempPeoples.add(p);
}
peoples = tempPeoples;
}
People luckPeople = peoples.get(0);
System.out.println(luckPeople);
}
public static boolean isCanUse(int code) {
for (People people : peoples) {
if (people.getCode() == code) {
return false;
}
}
return true;
}
}
package com.itheima.d1;
public class People {
private int code;// 编号
private int location;// 位置
public People() {
}
public People(int code, int location) {
this.code = code;
this.location = location;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public int getLocation() {
return location;
}
public void setLocation(int location) {
this.location = location;
}
@Override
public String toString() {
return "People{" +
"code=" + code +
", location=" + location +
'}';
}
}
方法2
package com.itheima.d1;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Test1 {
public static void main(String[] args) {
List<Integer> peoples = new ArrayList<>();
Random r = new Random();
for (int i = 1; i <= 100; i++) {
int code = r.nextInt(200) + 1;
if (peoples.contains(code)){
i--;
}else {
peoples.add(code);
}
}
System.out.println(peoples);
List<Integer> peoplesBak = new ArrayList<>();
peoplesBak.addAll(peoples);
//保留偶数位的到集合里去
while (peoples.size() > 1){
for (int i = peoples.size() % 2 == 0 ? peoples.size() - 2 : peoples.size() - 1; i >= 0; i-=2) {
peoples.remove(i);
}
}
int code = peoples.get(0);
System.out.println("幸存者编号" + code);
int indexOf = peoplesBak.indexOf(code);
System.out.println("幸存者位置" + (indexOf + 1));
}
}