java数组小游戏——数三退一
Count3Quit.java
//数3退1,小游戏算法测试
/*
若干个人围成一圈,从第一个人开始数,数到第三个人,第三个人退出,
继续从1开始数,到3退出
*/
public class Count3Quit {
public static void main(String[] args) {
//500个人拉成一圈,用数组模拟
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;//第0个人
while(leftCount > 1) {
if(arr[index] == true) {
countNum ++;
if(countNum == 3) {
countNum = 0;
arr[index] = false;
leftCount --;
}
}
index ++;
//如果index等于arr.length,index回0
if(index == arr.length) {
index = 0;
}
}
//找到剩下为true的数
for(int i=0; i<arr.length; i++) {
if(arr[i] == true) {
System.out.println(i);//i=435,下标为435,为第436个人
}
}
}
}
F:\java>javac Count3Quit.java
F:\java>java Count3Quit
435
F:\java>
Count3Quit2.java
/*
面向对象的写法:
数三退一,500个小孩围成一圈
*/
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.delete(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 delete(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 --;
}
}
F:\java>javac Count3Quit2.java
F:\java>java Count3Quit2
435
F:\java>