So, i need to implement this code that will return me the best solution of parentheses from a multiplication of matrices in java. I made a function for the printing of "(" ")" and in the main i did the construction of the matrices M and S for the resolution (dinamic programming). i keep getting this error after it prints the first "(":
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at ProgramacaoDinamica.parenterizacao(ProgramacaoDinamica.java:13)
at ProgramacaoDinamica.main(ProgramacaoDinamica.java:46)
code:
public class ProgramacaoDinamica {
private static int[][] s;
public static void parenterizacao(int[][] s, int i, int j) {
if (i == j) {
System.out.println("M" + i);
} else {
System.out.println("(");
parenterizacao(s, i, s[i][j]);
parenterizacao(s, s[i][j] + 1, j);
System.out.println(")");
}
}
public static void main(String[] args) {
int[] p = {15, 5, 10, 20, 25}; //VETOR P DO ENUNCIADO (alteracoes aqui!!!)
int n = p.length - 1;
int[][] m = new int[n][n];
int[][] s = new int[n - 1][n - 1];
for (int i = 0; i < n; i++) {
m[i][i] = 0;
}
for (int l = 1; l < n; l++) {
for (int i = 1; i <= l - n + 1; i++) {
int j = i + l - 1;
m[i][j] = 9999;
for (int k = i; k <= j - 1; k++) {
int q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j];
if (q < m[i][j]) {
m[i][j] = q;
s[i][j] = k;
}
}
}
}
parenterizacao(s, 1, n);
}
}
can anyone help me out with this? im starting to get lost with the code? im following this semi codes: java1 java2