----------------------------------------------------------------------------------------------------------------------------------------------------------

 泡牛吧!

                                       希望越来越多的光棍能够泡到牛

-----------------------------------------------------------------------------------------------------------------------------------------------------------

主题:母牛问题

package test;

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

/**
 * 牛产仔问题。有一头母牛,它每年年初要生一头小母牛;每头小母牛从第四个年头起, 每年年初也要生一头小母牛。按此规律,若无牛死亡,第20年头上共有多少头母牛?
 * @author
 */
public class Mooooo {

 public static final int yearCount = 20;

 public static final int yearHappyBirthday = 3;

 public static void main(String[] args) {
  
  List<Cow> cows = new ArrayList<Cow>(); // 牛群(冯巩不在)

  cows.add(new Cow(yearHappyBirthday)); // 第一个目牛

  ArrayList<Cow> newCows = new ArrayList<Cow>(); // 小牛群

  for (int i = 0; i < yearCount; i++) {
   for (Cow cow : cows) {

    if (cow.isHappyBirthday()) {
     newCows.add(new Cow(0)); // 生牛
    }
    cow = null;
   }
   cows.addAll(newCows); // 增加到牛群
   newCows.clear();
  }
  System.out.println("二十年光阴似箭,共有牛 " + cows.size() + " 头。");
  cows = null;
 }
 /**
  * 母牛
  */
 static class Cow {
  private int age = 0;

  public Cow(int age) {
   this.age = age;
  }

  public boolean isHappyBirthday() {
   age++;
   return age >= yearHappyBirthday ? true : false;
  }
 }
}

haohao   2007-03-10 14:49:27 评论:0   阅读:125   引用:0

发表评论>>

署名发表(评论可管理,不必输入下面的姓名)

姓名:

主题:

内容: 最少15个,最长1000个字符

验证码: (如不清楚,请刷新)

一切版权属于个人(转载例外)