javaalgorithmmatrix-multiplicationchainmmc

Why do I always get an ArrayIndexOutOfBoundsException?


This code is taken from a common algorithms book. The book uses an array starting from 1 instead of 0 for m but starts from 0 for p. How do I solve it ??

These are the errors:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at MMC_Test.MemoizedMatrixChain(MMC_Test.java:8)
at MMC_Test.main(MMC_Test.java:36)

and code here

public class MMC_Test {

public static int MemoizedMatrixChain(int[] p) {
    int n = p.length - 1;
    int[][] m = new int[n][n];
    for (int i = 1; i <= n; i++) {
        for (int j = i; j <= n; j++) {
            m[i][j] = Integer.MAX_VALUE;
        }
    }
    return lookUpChain(m, p, 1, n);
}// MemoizedMatrixChain

public static int lookUpChain(int[][] m, int[] p, int i, int j) {
    if (m[i][j] > Integer.MAX_VALUE) {
        return m[i][j];
    }
    if (i == j) {
        m[i][j] = 0;
    } else {
        for (int k = i; k <= j - 1; k++) {
            int q = lookUpChain(m, p, i, k) 
                    + lookUpChain(m, p, k + 1, j)
                    + p[i - 1] * p[k] * p[j];
            if (q < m[i][j]) {
                m[i][j] = q;
            }
        }
    }
    return m[i][j];
}

public static void main(String[] args) {
    // TODO Auto-generated method stub
    int[] arr = { 30, 35, 15, 5, 10, 20, 25 };
    int result = MemoizedMatrixChain(arr);
    System.out.println(result);

}// main

}


Solution

  • Change

    for (int i = 1; i <= n; i++) {
        for (int j = i; j <= n; j++) {
    

    to

    for (int i = 0; i < n; i++) {
        for (int j = i; j < n; j++) {
    

    and I haven't analyzed your code properly, but a guess is that

    return lookUpChain(m, p, 1, n);
    

    should be

    return lookUpChain(m, p, 1, n - 1);