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;
}
}
农夫养牛
最新推荐文章于 2025-05-27 18:19:13 发布