嗨,我最近一直在做 Project Euler 问题,但我在问题 18 上遇到了麻烦,这里是:
从下方三角形的顶部开始,移动到下方行中的相邻数字,从上到下的最大总数为 23。
3
7 4
2 4 6
8 5 9 3
即,3 + 7 + 4 + 9 = 23。
求下面三角形从上到下的最大总数:
75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23
注意:由于只有 16384 条路由,因此可以通过尝试每条路由来解决此问题。然而,问题 67 与包含一百行的三角形是相同的挑战;不能用蛮力解决,需要巧妙的方法! ;o)
我查找最大总数的算法是正确的。我通过在二维数组中手动输入数字来测试它,程序运行良好。我不想这样做的原因是因为这个问题说问题 67 是相同的,除了更大的数字,我不想整天输入数字,而且我想练习操作文件等。
无论如何,我认为我能做的最好的事情就是向您展示我的代码和我遇到的错误。我做了一些调试,这似乎就是我将数字字符串转换为数字数组的方式。当我运行该程序时,它给出了 ArrayIndexOutOfBoundsException()。 .txt 文件由上面问题描述中的一大组数字组成。
public static void main(String[] args) throws Exception
{
Problem18 p18 = new Problem18() ;
p18.maxTotalPath() ;
}
public int[][] readFile() throws Exception
{
ClassLoader loader = Thread.currentThread().getContextClassLoader() ;
InputStream file = loader.getResourceAsStream("Triangle.txt") ;
Scanner scan = new Scanner(file) ;
int[][] triangle = new int[15][15] ;
int m = 0, n = 0 ;
String line ;
while(scan.hasNext())
{
line = scan.nextLine() ;
String[] numbers = line.split(" ") ;
for(int i = 0 ; i < numbers.length ; i++)
{
triangle[m][n] = Integer.parseInt(numbers[i]) ;
//System.out.print(triangle[m][n] + " ") ;
n += 1 ;
}
n = 0 ;
// System.out.println("") ;
m += 1 ;
}
scan.close() ;
return triangle ;
}
public void maxTotalPath() throws Exception
{
int[][] arr = readFile() ;
for (int i = arr.length - 2 ; i >= 0 ; i--)
{
for (int j = 0 ; j < arr[i].length; j++)
{
arr[i][j] += Math.max(arr[i + 1][j], arr[i + 1][j + 1]);
}
}
System.out.println(Integer.toString(arr[0][0])) ;
}
错误是:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 15
at com.jconnolly.projeuler.problems.Problem18.maxTotalPath(Problem18.java:83)
at com.jconnolly.projeuler.problems.Problem18.main(Problem18.java:44)
任何帮助将不胜感激,谢谢!
最佳答案
嗯,您的 readFile
函数正在正常工作。您的 maxTotalPath 试图访问内部循环中的错误内存。如果j
一直到arr[i].length-1
,那么当您访问arr[i+1][j+1]
时code>,您将到达超出数组范围的内存。
for (int j = 0 ; j < arr[i].length-1; j++)
{
arr[i][j] += Math.max(arr[i + 1][j], arr[i + 1][j + 1]);
}
更正错误答案
我认为这就是你需要做的
for (int j = 0 ; j < arr[i].length; j++)
{
if (j != arr[i].length-1) {
arr[i][j] += Math.max(arr[i + 1][j], arr[i + 1][j + 1]);
} else {
arr[i][j] += arr[i+1][j];
}
}
关于java - 将文件读入二维数组 - 获取 ArrayIndexOutOfBoundsException(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18020953/