import java.util.Arrays;
public class Tes {
public static void main(String[] args) {
// 数3退1;每数到3就退出一个人,求最后剩下一个人的下标;
boolean people[] = new boolean[500];
Arrays.fill(people, true);
int count = 0;//记录该人为第几个数(循环)
int length = people.length;// 数组内为true值的总数
while (length > 1) {// 当值为true的数只有一个时,结束循环
for (int i = 0; i < people.length; i++) {// 确认数组内每个数的值
if (people[i]) {// 确认数组内为true的有效值 ,为false表示已经移除
count++;
/*
* 在此容易犯的错
* 思路:为true值时,才会有后续操作,为false,什么都不变化
* 所以,下一个if条件为该if的子条件,在大括号里面,不在外面
* 如果将下个if与当前if平级
* 举例:当进行第2轮遍历时
* 501=ture, i=0,count%3=0,people[0](501)=false,length--;
* 502=ture,i=1,count%3=1,people[1](502)=false,length--;
* 503=false,i=2,count%3=0,people[2](503)=false,length--;
*
* 可以看出,为false时,length,同样会减少,算法逻辑出现错误*/
if (count % 3 == 0) {// 移除人员,并减少值为true的总人数
people[i] = false;
length--;
}
}
}
}
// 循环,判断,输出最后剩下值为true的下标+1(编号从1开始)
for (int j = 0; j < people.length; j++) {
if (people[j])
System.out.println("剩余的小孩的编号为:" + (j + 1));
}
}
}