您好我最近一直在处理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)
非常感谢任何帮助,谢谢!
答案 0 :(得分:0)
maxTotalPath内部循环应该转到arr [i] .length - 1,这将至少停止异常
答案 1 :(得分:0)
嗯,您的readFile
功能正常运行。您的maxTotalPath
正在尝试访问内循环中的错误内存。如果j
一直到arr[i].length-1
,那么当您访问arr[i+1][j+1]
时,您将获得超出数组范围的内存。
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];
}
}