我只是在Java中测试河内塔问题,我运行了以下代码:(为方便起见,我已删除)sysouts
public class Util {
public static void main(String[] args) {
for (int i = 1; i <= 30; i++) {
long startTime = System.currentTimeMillis();
solveTowerOfHanoi(i, "A", "B", "C");
System.out.println("Time taken for " + i + ": "
+ (System.currentTimeMillis() - startTime));
}
}
public static void solveTowerOfHanoi(int n, String src, String inter,
String dest) {
if (n == 0) {
return;
}
solveTowerOfHanoi(n - 1, src, dest, inter);
solveTowerOfHanoi(n - 1, inter, src, dest);
}
}
我做了一个实验,我尝试了从 1 到 35 的磁盘大小(索引),我观察到一个非常奇怪的时序模式,这是程序的输出:
Time taken for 1: 0
Time taken for 2: 0
Time taken for 3: 0
Time taken for 4: 0
Time taken for 5: 0
Time taken for 6: 0
Time taken for 7: 0
Time taken for 8: 1
Time taken for 9: 0
Time taken for 10: 0
Time taken for 11: 0
Time taken for 12: 0
Time taken for 13: 0
Time taken for 14: 0
Time taken for 15: 0
Time taken for 16: 0
Time taken for 17: 0
Time taken for 18: 3
Time taken for 19: 2
Time taken for 20: 11
Time taken for 21: 10
Time taken for 22: 39
Time taken for 23: 37
Time taken for 24: 158
Time taken for 25: 147
Time taken for 26: 603
Time taken for 27: 579
Time taken for 28: 2414
Time taken for 29: 2304
Time taken for 30: 9509
Time taken for 31: 9408
Time taken for 32: 38566
Time taken for 33: 37531
Time taken for 34: 152255
Time taken for 35: 148704
问题 1:算法有指数增长(2^n-1),那么为什么我看不到从 1-20 的时间逐渐增长?但是然后突然从20-35跳跃?
问题2:还有一件更让我吃惊的事情是成对的时间相等。从 19 日开始,(19,20)、(21,22)、(23,24)、(25,26) 等......有可比的时间。我无法理解这一点,如果算法的增长率确实是指数级的,为什么两个索引给出几乎可比的时间,然后在下一个索引处突然跳跃?
注意:我重复了这个程序 2-3 次,得到了几乎可比的时间,所以你可以把它当作一个平均运行。
编辑
尝试System.nanoTime()
并得到以下结果:
Time taken for 1: 62644
Time taken for 2: 3500
Time taken for 3: 3500
Time taken for 4: 4200
Time taken for 5: 6300
Time taken for 6: 7350
Time taken for 7: 11549
Time taken for 8: 19948
Time taken for 9: 47245
Time taken for 10: 73142
Time taken for 11: 87491
Time taken for 12: 40246
Time taken for 13: 39196
Time taken for 14: 156784
Time taken for 15: 249875
Time taken for 16: 593541
Time taken for 17: 577092
Time taken for 18: 2318166
Time taken for 19: 2305217
Time taken for 20: 9468995
Time taken for 21: 9082284
Time taken for 22: 37747543
Time taken for 23: 37230646
Time taken for 24: 150416580
Time taken for 25: 145795297
Time taken for 26: 603730414
Time taken for 27: 578825875
Time taken for 28: 2409932558
Time taken for 29: 2399318129
Time taken for 30: 9777009489
输出几乎与毫秒相似,但它确实使画面清晰......回答我的问题 1可能是,但问题 2仍然很有趣。并System.nanoTime()
提出了另一个问题:
问题 3:为什么索引 1 比下一个索引 (2,3...) 等花费更多时间?