1.循环报数游戏,有n个人,从1到k报数,报道k 的退出游戏,得出最后获胜人的编号,编号从0开始。
思路:
一.创建大小为 n 的boolean类型的数组,并把所有元素初始化为true;
二.使用while循环,循环的条件为获胜的人数大于1。从0下标位置开始循环判断,这里分为三种情况:
1.index位置的值为true ,且count ==k ,这种情况是找到了退出游戏的人。则把这个位置的值改为false;活着的人数减一,计数继续从1开始计数。
2.index位置的值为true,且count != k;这种情况是还没有找到k位置的人,则继续报数,index++,count++;
3.index位置的值为false ,这种情况是index位置的人已经退出游戏,则count不需要加加,index++就行。
三.找到数组里唯一一个值是true的下标并返回;
下面是代码实现:
public static int CyclicGame(int n, int key) {
//创建一个大小为 n 的boolean类型数组,所有元素初始化为true;
boolean[] array = new boolean[n];
for (int i=0; i<n; i++) {
array[i]=true;
}
//count 报数,index 数组下标,peopleLeft 活着的人数。
int count = 1;
int index = 0;
int peopleLeft = n;
//只要活着的人大于1就继续循环。
while (peopleLeft >= 2) {
//如果index下标的值为true且满足报数到k。则把这个下标的值改为flase;
//则活着的人peopleLeft--,报数继续从1 开始报数 count =1;
if (array[index] == true && count == key) {
array[index] = false;
peopleLeft --;
count = 1;
} else if (array[index] && count != key) {
//如果index下标的值为true 且count 的值不为k。则count++;index++;
count ++;
index = (++ index) % n;
}
else {
//如果index下标的值为flase,则只需index++;
index = (++ index) % n; //[0, n-1]
}
}
//找活着的那个;
for (int i=0; i<n; ++i) {
if(array[i]) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
System.out.println(CyclicGame(4, 3));
}
这里只是个人的学习总结。有什么问题欢迎提意见。