0
public class Dynamic_Programming {

public static int HowManyWays(int n)
{
    int [] mem = new int[]{0,1};
    for(int i = 2; i <= n; i++)
    {
        int sum = 0;
        for(int k =1; k <= n-1; k++)
        {
            sum += mem[k]*mem[n-k];
        }
        mem[i] = sum;
    }
    return mem[n];
}

public static void main (String [] args)
{
    long startTime = System.nanoTime();
    System.out.println("For 2 matracies: " + HowManyWays(2));
    long totalTime = System.nanoTime()-startTime;
    System.out.println("Time in nanoseconds: " + totalTime);
}

}

This is the code for a simple method that uses the dynamic programming technique in order to determine the number of ways to multiply n matrices together. However I keep getting and ArrayIndexOutOfBounds error when I run the program. It tells me that the problem is with this line of code right here. mem[i] = sum;. Some guidance on how to fix this problem would be greatly appreciated.

Kaustubh Khare
  • 3,280
  • 2
  • 32
  • 48
Eddie White
  • 327
  • 2
  • 4
  • 10
  • 2
    Your `mem` stores sum at index 2. Why you are starting loop from 2 ?? – Kaustubh Khare Oct 30 '17 at 05:33
  • 2
    When `i = 2`, you're trying to set `mem[2] = sum`, but `mem` only has a size of 2 (`mem[0]` and `mem[1]`). – Irfan434 Oct 30 '17 at 05:36
  • 1
    mem[i] = sum; //This statement is throwing Exception , reason is the array size is 2 {arr[0] and arr[1]} as index of array starts from 0 and the statement mem[i] = sum; which means at i index of mem array assign value of sum , but i is initialized as 2 , which means you are trying mem[2]=sum , which doesn't exist – Monis Majeed Oct 30 '17 at 05:38
  • Wow thanks so much, I don't know why I didn't see that sooner. – Eddie White Oct 30 '17 at 05:45

1 Answers1

0

You only have two elements in your array. Arrays start at 0. When mem[i] is referenced it is trying to invoke the element in the array at index i. Since i = 2 in this case it will take throw an exception.

Demuze28
  • 13
  • 8