老鼠生子问题

来源:互联网 发布:纯js省市区三级联动 编辑:程序博客网 时间:2024/04/28 03:42

很久没自己动手写过程序了,今天从一个QQ群里看到有人问这个问题,就想自己动手试一下,结果手足无措,发现自己真的是老了,智商跟不上了。

算法什么的,什么也不会了,刚接触了几天 Java,试着用 Java 写了一下,不知道写的对不对?

经典的耗子生子问题。
假设一对耗子每个月都可以生一对小耗子。小耗子生长3个月后,从第4个月开始也就能够生小耗子。
问:假设所有的耗子都不死的话,那么20个月后一共有多少只耗子?

import java.util.ArrayList;public class MyTest{public static void main(String[] args){MiceCouple m = new MiceCouple();int count = 0;for(int i = 0; i < 20 ; i++){m.grow();count = m.getChildrentCount() + 1;System.out.println("" + count);}count = m.getChildrentCount() + 1;System.out.println("" + count);}}class MiceCouple{private int age;private ArrayList<MiceCouple> children;public MiceCouple(){this.age = 0;this.children = new ArrayList<MiceCouple>();}public void grow(){this.age++;if(this.age > 3)this.breed();for(MiceCouple m : this.children){m.grow();}}private void breed(){children.add(new MiceCouple());}public int getChildrentCount(){int sum = 0;for(MiceCouple m : children){sum += m.getChildrentCount();}sum += children.size();return sum;}}

结果:(20个月)
1
1
1
2
3
4
6
9
13
19
28
41
60
88
129
189
277
406
595
872

 

原创粉丝点击