java 代码
- import java.util.ArrayList;
- /**
- * 牛产仔问题。有一头母牛,它每年年初要生一头小母牛;每头小母牛从第四个年头起,
- * 每年年初也要生一头小母牛。按此规律,若无牛死亡,第20年头上共有多少头母牛?
- *
- * @author
- */
- public class Mooooo {
- public static void main(String[] args) {
- ArrayList<cow> cows = new ArrayList<cow>(); </cow>// 牛群(冯巩不在) </cow>
- cows.add(new Cow(3));
- for (int i = 0; i < 20; i++) {
- ArrayList<cow> newCows = new ArrayList<cow>(); </cow>// 小牛群 </cow>
- for (Cow cow : cows) {
- cow.happyBirthday(newCows);
- }
- cows.addAll(newCows);
- }
- System.out.println("二十年光阴似箭,共有牛 " + cows.size() + " 头。");
- }
- /**
- * 母牛
- */
- static class Cow {
- private int age = 0;
- public Cow(int age) {
- this.age = age;
- }
- public void happyBirthday(ArrayList<cow> cows) { </cow>
- age++;
- if (age >= 3) {
- cows.add(new Cow(0));
- }
- }
- }
- }