牛生牛的问题

来源:互联网 发布:nvslp监控软件下载 编辑:程序博客网 时间:2024/06/08 05:48

以前记得在学习java的时候留了一个牛生牛的问题没有解决,今晚突然想起了于是就简单的写了一下,问题大概如下:初生小牛到五岁才能再生小牛,现在农场有一头初生小牛,20年后一共会有多少头

package sina.CreAmazing.sf;import java.util.ArrayList;public class Test1 {/** * @param args */public static void main(String[] args) {//为农场添加初始的小牛ArrayList<Cow> c = new ArrayList<Cow>();c.add(new Cow(0));//c.add(new Cow(1));Farm f = new Farm(c);f.product(20);}}class Cow {int age;public Cow(int age) {super();this.age = age;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}Cow giveBirth() {return new Cow(0);}}class Farm {public Farm() {super();this.cows.add(new Cow(0));}public Farm(Cow c) {super();this.cows.add(c);}public Farm(ArrayList<Cow> cows) {super();this.cows = cows;}ArrayList<Cow> cows = new ArrayList<Cow>();void product(final int year) {new Thread() {public void run() {for (int i = 0; i < year; i++) {for (int k =0;k < cows.size();k++  ) {cows.get(k).setAge(cows.get(k).getAge()+1);if (cows.get(k).getAge() >= 5) {Cow c = cows.get(k).giveBirth();cows.add(c);}}System.out.println((i+1)+" year past and the number of cows are " + cows.size());try {sleep(100);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}};}.run();}}

结果:

1 year past and the number of cows are 1
2 year past and the number of cows are 1
3 year past and the number of cows are 1
4 year past and the number of cows are 1
5 year past and the number of cows are 2
6 year past and the number of cows are 3
7 year past and the number of cows are 4
8 year past and the number of cows are 5
9 year past and the number of cows are 7
10 year past and the number of cows are 10
11 year past and the number of cows are 14
12 year past and the number of cows are 19
13 year past and the number of cows are 26
14 year past and the number of cows are 36
15 year past and the number of cows are 50
16 year past and the number of cows are 69
17 year past and the number of cows are 95
18 year past and the number of cows are 131
19 year past and the number of cows are 181
20 year past and the number of cows are 250


挺简单的算是给初学者吧

原创粉丝点击