0

I've implemented a DP algorithm that finds the longest common subsequence in three arrays. The problem though, is that my algorithm doesn't work when the arrays are of different lengths, and I have no idea why. From what I can tell, my algorithm is correct, so I think it's something to do with the Java implementation. Here is my Java code:

static int[] lcsOf3(int[] X, int[] Y, int[] Z, int xLength, int yLength, int zLength) {
        int[][][] S = new int[xLength + 1][yLength + 1][zLength + 1];

        for (int i = 0; i <= xLength; i++) {
            for (int j = 0; j <= yLength; j++) {
                for (int k = 0; k <= zLength; k++) {
                    if (i == 0 || j == 0 || k == 0) {
                        S[i][j][k] = 0;
                    } else if (X[i - 1] == Y[j - 1] && X[i - 1] == Z[k - 1]) {
                        S[i][j][k]= S[i - 1][j - 1][k - 1] + 1;
                    } else {
                        S[i][j][k] = Math.max(Math.max(S[i - 1][j][k], S[i][j - 1][k]), S[i][j][k - 1]);
                    }
                }
            }
        }
        System.out.println(S[xLength][yLength][zLength]);
}
Ninjaman494
  • 180
  • 3
  • 10
  • I would rather find LCS between first two arrays and use that result to find LCS with third array. You don't need to deal with 3 d arrays. – SomeDude Oct 29 '18 at 01:56
  • On the first, it looks like line with max() should check all 7 possibilities how current string (i,j,k) can be 'approached'. All combinations of indices x and x-1. – Ante Oct 30 '18 at 13:07

1 Answers1

0

I took another look at my code,and it turns out that it was something with my implementation, not the algorithm itself. There was a bug in the part of my code that gets the input arrays(X,Y,Z). After fixing the bug, it works correctly on lists of different sizes.

Thanks to everyone who tried to help out, and sorry for wasting your time.

Ninjaman494
  • 180
  • 3
  • 10