猴子选大王游戏
/**
*total只猴子围成一个圈报数,报到数字king的猴子退出,最后一只猴子就是猴王,输出猴王的初始序号
*/
import java.util.Scanner;
public class monkeyKing {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入猴子选大王的数字");
int king = sc.nextInt();
System.out.println("请输入猴子个数");
while (sc.hasNext()){
int total = sc.nextInt();
System.out.println(countNum(total,king)+1);
}
}
public static int countNum(int total,int king){
if(total<=0||king<=0){
return 0;
}
if(total==1){
return 1;
}
//默认值=0,出局时改为1
boolean[] arr = new boolean[total];
//初始数组下标
int index = -1;
//循环报的数
int start = 0;
//累计出局个数(报数循环次数)
int count = 0;
//不确定循环次数--while循环
while (true){
start++;
index++;
if(index==total){
index=0;
}
while (arr[index]==true){
index++;
if(index==total){
index=0;
}
}
if(start==king){
//准备退出圈子,将数组的值改为0
count++;
if(count==total){
return index;
}
arr[index]=true;
//猴子编号从1开始,数组下标从0开始,此处+1
System.out.println("出局的猴子编号:"+(index+1));
start=0;
}
}
}
}