农夫养牛

package excise;

import java.util.ArrayList;
import java.util.List;

/** 
 * 问题描述: 
 *  
 * 一头母牛在3—10岁的时候每年可以生一头小牛,生公牛和母牛的比率是50%, 
 * 在牛12岁的时候就送入屠宰场买了。现在有一个农夫有1头1岁大的母牛, 
 * 在母牛3岁的时候就送到附近的农场去配种,请问40年后这个农夫可能会有多少头牛, 
 * 写出相关的代码或答题思路,最好用面向对象。 
 * 
 */ 

public class ComputeCattles {
	// 保存所有母牛
	private static List<Cattle> cows = new ArrayList<Cattle>();

	// 保存所有当前农夫拥有的牛
	private static List<Cattle> cattles = new ArrayList<Cattle>();

	public static void main(String[] args) {
		// 第一头母牛
		Cattle cow = new Cattle(0, 3);
		cows.add(cow);

		for (int i = 0; i < 40; ++i) {		// 40年
			// 每年,所有的牛,大于等于12岁的牛送到屠宰场卖掉
			for (int j = 0; j < cattles.size(); ++j) {
				Cattle temp = cattles.get(j);
				if (temp.getDead()) {
					cattles.remove(temp);
				}
				// 所有牛都在长
				cattles.get(j).grow();
			}

			// 一头母牛生一头小牛
			for (int j = 0; j < cows.size(); ++j) {
				Cattle calf = cows.get(j).bear();
				if (calf != null) {
					if (calf.getSex() == 0)
						cows.add(calf);
					cattles.add(calf);
				}
			}
		}
		System.out.println("40年后农夫可能拥有" + cattles.size() + "头牛");
	}
}

class Cattle {
	private int sex;
	private int age;

	private boolean dead = false;

	public Cattle() {
	}

	public Cattle(int sex, int age) {
		this.sex = sex;
		this.age = age;
	}

	public Cattle bear() {
		Cattle calf = null;
		if (this.sex == 0) {
			calf = birth();
		}
		return calf;
	}
	
	private Cattle birth() {
		Cattle calf = null;
		if (this.age >= 3 && this.age <= 10) {
			calf = new Cattle(random(), 0);
		}
		return calf;
	}

	private int random() {
		return (int) Math.round(Math.random());
	}

	public void grow() {
		this.age++;
	}

	public int getSex() {
		return this.sex;
	}

	public boolean getDead() {
		if (this.age >= 12)
			dead = true;
		return this.dead;
	}

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值