【发布时间】:2014-03-22 02:24:30
【问题描述】:
情况是这样的——斐波那契通过研究一对每月繁殖的兔子和另一对会繁殖的兔子,开发了他的递归序列 f(n) = f(n-1) + f(n-2)下个月。 我正在改变这种情况,以便它们不会在第一个月后重现,而是在第二个月后重现。 我的输出中的数字是正确的。但是,我的问题是 45 个月后,由于某种原因,我收到了 Java 堆空间错误。 我曾尝试使用 long 和 double 但无济于事。请让我知道你的想法。 代码:
import java.util.*;
import java.io.*;
import java.lang.System.*;
public class Rabbits {
public static void main(String[] args) throws IOException{
Scanner in = new Scanner(new File("rabbits.dat"));
int numSets = Integer.parseInt(in.nextLine().trim());
for(int curSet = 0; curSet<numSets; curSet++){
ArrayList<Integer> population = new ArrayList<>();
population.add(0);
int months = Integer.parseInt(in.nextLine().trim());
for(int i = 0; i < months; i++){
int matured = 0;
for(int pos = 0; pos<population.size(); pos++){
population.set(pos, population.get(pos)+1);
if(population.get(pos)>=3){
matured++;
}
}
for(int n = 0; n<matured; n++){
population.add(0);
}
}
System.out.println("Months: " + months + " Population: " + population.size());
}
}
}
有输入:
28
1
2
3
4
5
6
7
8
9
10
15
20
25
30
35
40
45
50
55
60
65
70
75
80
85
90
95
100
和输出:
--------------------Configuration: <Default>--------------------
Months: 1 Population: 1
Months: 2 Population: 1
Months: 3 Population: 2
Months: 4 Population: 3
Months: 5 Population: 4
Months: 6 Population: 6
Months: 7 Population: 9
Months: 8 Population: 13
Months: 9 Population: 19
Months: 10 Population: 28
Months: 15 Population: 189
Months: 20 Population: 1278
Months: 25 Population: 8641
Months: 30 Population: 58425
Months: 35 Population: 395033
Months: 40 Population: 2670964
Months: 45 Population: 18059374
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:2245)
at java.util.Arrays.copyOf(Arrays.java:2219)
at java.util.ArrayList.grow(ArrayList.java:213)
at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:187)
at java.util.ArrayList.add(ArrayList.java:411)
at Rabbits.main(Rabbits.java:22)
Process completed.
【问题讨论】:
-
尝试将计数保持为 long 并增加它,而不是拥有大量的数字 0 数组,这些数组将被一遍又一遍地复制......
-
我不知道我该怎么做。我必须跟踪每只兔子,以确保它们在 3 个月大时开始繁殖。
-
您可以通过创建一个公式来描述每一代的前身。试图跟踪每只兔子的年龄将需要 很多 更多的内存——可能在 TB 的数量级上。