I am trying to find trinomial coefficients and I want to avoid using negative index in my array. There will be instances whereby i or j will become negative and will return array out of bounds error. Is there anyway I can mirror the array contained in the negative indexes to a positive index?
Here’s the recursive formula: Recursion Formula
I recognize that T(0, -1) = T(0, 1)
but how do I implement it?
example:
row 0: T(0, 0) = 1 , T(0, 1) = 0 ...
row 1: T(1, 0) = T(0, -1) + T(0, 0) + T(0, 1) , T(2, 0) ...
The trinomial coefficient T(n,k)
is the coefficient of x^(n+k)
in the expansion of (1+x+x^2)^n
.
Trinomial triangle (middle index is 0
, negative on the left of 0
, positive on the right of 0
):
Note: The code below iterates through the array from middle index 0
to the right.
public class ClassNameHere {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
int k = Integer.parseInt(args[1]);
long[][] DP = new long[n + 1][k + 1];
DP[0][0] = 1;
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= Math.min(i, k); j++) {
if (i == j || ((j == 0) && i < 2)) DP[i][j] = 1;
else if (j < -i) {
DP[i][j] = 0;
} else DP[i][j] = DP[i - 1][j];
}
}
System.out.println(DP[n][k]);
}
}
Now I am able to get the terms from T(0, 0)
to T(1, 0)
with my code but unable to continue past T(2, 0)
onwards by adding T(1,0) + T(1, 1) + T(1, 2)
. When I tried to implement DP[i][j] = DP[i - 1][j - 1] + DP[i - 1][j] + DP[i - 1][j + 1]
, it returns ArrayIndexOutOfBoundsException
again.. I think that something is wrong with the implementation of the above statement ^
. Any suggestions on how to go on with this?