所有人围成一个圈,数到3的人就退出,问最后留下的那个人的位置在那里
2013-10-16 22:18
399 查看
约瑟夫环问题-所有人围成一个圈,数到3的人就退出,问最后留下的那个人的位置在那里?
第一种方法
public class Count3Quit{
public static void main(String []args){
//定义一个数组用来当做500个人.并且初始化为true表示都在圈内
boolean arr[] =new boolean[500];
for(int i=0; i<arr.length; i++){
arr[i]=true;
}
//定义一个总人数
int count=arr.length;
//定义一个索引位置,表示当前在那个位置
int index=0;
//计数器,数到3退出
int countNum=0;
//如果只剩下最后一个人就退出循环
while(count>1){
if(arr[index]==true){ //如果当前的这个人在圈内就开始数数
countNum++;
if(countNum==3){
countNum=0; // 如果数到3了就要把计数器归0
arr[index]=false; //表示这个人已经退出
count--; //总人数减去一个
}
}
index++;
if(index==arr.length){
index=0;
}
}
//找到最后一个在圈子内的人的下标位置
for(int i=0 ;i<arr.length; i++){
if(arr[i]==true){
System.out.println("最后剩下的一个人在第"+(i+1)+"个位置");
}
}
}
}
第二种方法(面向对象的思想)
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 --;
}
}
相关文章推荐
- 有10人围成圈数数,每次数到3的人退出其他人继续,问最后剩下的一个人原来的位置是多少
- P123.32(有57个人围成一个圈,顺序排号,从第一个人开始报数(从1~4报数),凡报到四的人退出圈子,问最后留下的是原来的几号?)
- 有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来第几号的那个人。
- 有10人围成圈数数,每次数到3的人退出其他人继续,问最后剩下的一个人原来的位置是多少
- n个人围成一个圈,顺序排号,按1,2,3循环报数,凡是报到3的人退出,问最后留下的 是原来的第几号那位
- 3 耶稣有13个门徒,其中有一个就是出卖耶稣的叛徒,请用排除法找出这位叛徒:13人围坐一圈,从第一个开始报号:1,2,3,1,2,3...。凡是报到“3”就退出圈子,最后留在圈子内的人就是出卖耶稣的
- 有n个人围成一圈,顺序排号,从第一个人开始报数(从1-3报数) 凡报到3的人,退出圈子,问最后留下的那位,是原来的第几号。
- 有n个人围成一圈,顺序排号,从第一个人开始报数(从1~3报数),凡报到3的人退出圈子,问最后留下的人原来排在第几号。
- 有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来第几号的那位。
- python中获得一个字符串最后出现位置
- 有N个人围成一圈,顺序排号。从第一个开始报数,(从1到3报数),凡报道3的人退出圈子,问最后留下的是原来第几号那位
- 整数算法训练02—有n个人围成一圈,顺序排号,从第一个开始报数(从1到3报数),凡报到3的人退出圈子,问最后最后留下的是原来第几号的那位
- 返回一行中相对数字比较集中最后的一个索引位置
- 有N个人围成一圈,顺序排列.从第一个人开始报数(从1—>3),凡报到3的退出圈子。问最后留下的是原来第几号的那位?
- 耶稣有13个门徒,其中有一个就是出卖耶稣的叛徒,请用排除法找出这位叛徒:13人围坐一圈,从第一个开始报号:1,2,3,1,2,3...。凡是报到“3”就退出圈子,最后留在圈子内的人就是出卖耶稣的叛徒。
- 只有一个执行几秒的作业为什么在taskctl中要执行很久且最后自动退出了-释疑
- 有1-m个数,围成一圈,从第一个开始数,数到n的数退出,输出最后剩下的那个数
- 有n个人围成一圈,顺序排号,从第一个开始报数(从1到3报数),凡报到3的人退出圈子,问最后最后留下的是原来第几号的那位.
- 有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来第几号的那位
- 返回一行中相对数字比较集中最后的一个索引位置(downmoon)