数3退1

问题:

500个小孩站成一圈,123报数,报到3的小孩就退出,问最后剩下的小孩是几号?

对象思想:

public class Count3Quit {<span style="white-space:pre">						</span>//游戏规则

	public static void main(String[] args) {
		KidCircle kc=new KidCircle(500);
		int count=0;
		Kid k=kc.first;
		int leftKid=kc.count;
		while( leftKid>1) {
			count++;
			if(count==3) {
				kc.delete( k);
				count=0;
				leftKid--;
			}
			k=k.right;			
		}
		System.out.println( k.id);		
	}
}

class Kid {<span style="white-space:pre">								</span>//小孩个体
	int id;
	Kid left;
	Kid right;
}

class KidCircle {<span style="white-space:pre">							</span>//小孩手拉手
	int count;
	Kid first;
	Kid 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 {
			k.left=last;
			k.right=first;
			last.right=k;
			first.left=k;
			last=k;
		}
		count++;
	}
	
	void delete( Kid k) {
		if( count ==0) {
			return;			
		} else if (count ==1) {
			first=null;
			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;
			}			
		}
	}
}

过程思想1:

public class Count3Quit {
	public static void main( String[] args) {
		boolean[] kc=new boolean[500];<span style="white-space:pre">				</span>//用true,flase代替delete操作
		for(int i=0;i<500;i++) {
			kc[i]=true;
		}
		int leftKid=500;<span style="white-space:pre">					</span>//剩余小孩个数
		int count=0;<span style="white-space:pre">						</span>//报数
		int index=0;<span style="white-space:pre">						</span>//小孩序号
		while(leftKid>1) {
			if(kc[index]==true) {
				count++;
				if(count==3) {
					kc[index]=false;	
					leftKid--;
					count=0;
				}
			}				
			index++;
			if(index==500) {
				index=0;
			}				
		}
			
				
		
		
		for(int i=0;i<500;i++) {
			if( kc[i]==true) {
				System.out.println( i);
			}				
		}
	}
}

过程思想2:

因为每3下报数,出去一个人,最多报1500次。所以可以建立一个长度为1500的数组。将1-500连续放3次。
每3个数出去一个,将后面对应位置上的数也去掉。那么最后只剩下一个。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值