数三退一问题

游戏规则:

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 --;
	}
	
}
	



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值