1

嗨,我最近一直在做 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)

任何帮助将不胜感激谢谢!

4

2 回答 2

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];
    }
}
于 2013-08-02T15:43:21.737 回答
0

maxTotalPath 内部循环应该去 arr[i].length - 1,这至少会停止异常

于 2013-08-02T15:43:15.043 回答