题目:
有100个萝卜,一只兔子边背边吃,走一米吃一个,走到家剩下多少萝卜,(到家一共50米,兔子每次只能背50个)。
假设:
兔子行动距离是离散的,即最小行动单位是1米。
代码实现:
package CarrotAndRabbit;
public class CarrotAndRabbitForDiscrete {
privateintcarrots= 0;
privateintdistance= 0;
privateintcapacity= 0;
privateintcarrots_rest= 0;
privateintdistance_rest= 0;
public CarrotAndRabbitForDiscrete(intcarrots,intdistance,intcapacity) {
this.carrots=carrots;
this.distance=distance;
this.carrots_rest=carrots;
this.distance_rest=distance;
this.capacity=capacity;
}
public int results() {
while(distance_rest> 0){
this.forwardOneMeter();
}
return this.carrots_rest;
}
public void conditions(){
System.out.println("Distance: "+distance+" ,Carrots: "+carrots);
}
private void forwardOneMeter() {
intmax_num= 0;
intdiscard_carrots= 0;
if(carrots_rest%capacity> 2){
max_num=carrots_rest/capacity+ 1;
}else{
max_num=carrots_rest/capacity;
discard_carrots=carrots_rest%capacity;
}
this.carrots_rest-=discard_carrots;
if(max_num< 1) {
this.carrots_rest= 0;
this.distance_rest= 0;
}elseif(max_num== 1) {
this.carrots_rest--;
this.distance_rest--;
}else{
this.carrots_rest=this.carrots_rest- 1 - (max_num- 1) * 2;
this.distance_rest--;
}
//System.out.println(carrots_rest + ":" + distance_rest);
}
public static void main(String...strings) {
CarrotAndRabbitForDiscretecarrotAndRabbit=newCarrotAndRabbitForDiscrete(100, 50, 50);
System.out.println(carrotAndRabbit.results());
}
}