游戏规则:
500人围成一个圈,从第一个开始数,数到三的人退出,求最后一个人的编号
一、数组方法
arr[]--模拟人
leftCount--剩余的人
countNum-数三计数器
index--当前指向的人
public class Count3Quit {
public static void main(String[] args){
boolean[] arr = new boolean[500];
for(int i=0; i<arr.length; i++){ //构造一个布尔类型的数组模拟人
arr[i] = true;
}
int leftCount = arr.length;
int countNum = 0;
int index = 0;
while(leftCount >1){ //当剩余人大于1时循环
if( arr[index]==true ){ //当数组内容为真时,计数器+1
countNum++;
if(countNum == 3){
countNum = 0;
arr[index] = false; //计数器数到三,计数器归0,数组变为假,剩余人数减1
leftCount --;
}
}
index++; //继续数下一个人
if(index == arr.length){ //数到最后一个从头数
index = 0;
}
}
for(int i=0; i<arr.length; i++){
if(arr[i]==true){
System.out.println(i);
}
}
}
}
二、面向对象的思路
创建两个类
1.Kid——
属性:编号ID(int) 、左边的人left(kid类)、 右边的人right(kid)
2.KidCircle——
属性:首位first 、last(Kid类) 记录多少人count(int)
方法: 构造方法——循环添加人
add方法——向圈的尾端加一个人
deletle方法——删除一个人,左右连接起来
public class Count3Quit2 {
public static void main(String[] args){
KidCircle kc = new KidCircle(500);
int countNum = 0;
Kid k = kc.first;
while( kc.count >1 ){
countNum ++;
if(countNum == 3){
countNum = 0;
kc.deletle(k);
}
k = k.right;
}
System.out.println(kc.first.id);
}
}
class Kid{
int id;
Kid left;
Kid right;
}
class KidCircle{
int count = 0; //圈中有多少人
Kid first, last; //圈的首位
KidCircle(int n){
for(int i=0; i<n; i++){
add();
}
}
void add(){
Kid k = new Kid();
k.id = count;
if(count <= 0){
first = k;
last = k;
k.left = k;
k.right = k;
}else{
last.right = k;
k.left = last;
k.right = first;
first.left =k;
last = k;
}
count++;
}
void deletle(Kid k){
if(count <=0){
return;
}else if (count == 1){
first = last = null;
}else{
k.left.right = k.right;
k.right.left = k.left;
if(k == first){
first =k.right;
}else if (k == last){
last = k.left;
}
}
count --;
}
}