有N个小孩围成一圈,从1-3报数,报到3的出列,编码实现小孩出列顺序。
【随便一个方向,1-3的排,是3的出局】
提示:用到Boolean
实现:
public class WeiQuan {
public static void main(String[] args) {
boolean[] array = new boolean[30];// 默认数组的30个元素是false
joyloop(array);
}
public static void joyloop(boolean[] array) {
// 将数组元素置为true
for (int i = 0; i < array.length; i++) {
array[i] = true;
}
int counter = 0;// 计数器
int leftCount = array.length;// 剩余人数
int index = 0;// 索引
// 当剩余总人数大于1,进行出列游戏
while (leftCount > 1) {
if (array[index]) {
counter++;
System.out.print(counter + " ");
if (counter == 3) {
System.out.println("----------重新计数----------");
counter = 0;
array[index] = false;
System.out.println("第 " + (index + 1) + " 位置的人出局");// 这里的位置是实际位置,不是索引位置
leftCount--;// 将出局的人减掉
}
}
index++;
// 当该位置索引等于数组长度时,置索引为0,防止if (array[index]) 数组越界
if (index == array.length) {
index = 0;
System.out.print("【防止数组越界】");
}
}
System.out.println("--------------------------");
for (int i = 0; i < array.length; i++) {
if (array[i]) {// 最后剩下的array[i]为true的就是这个人所处的位置
System.out.println("剩余人员的位置是" + (i + 1));
}
}
}
}