Find Proper Longest Common Subsequence

97 views Asked by At

I am trying to find proper longest common subsequence. I used below code and I was expecting 'B' as a result, however I am getting output as {K,B,C} which is not expecting. Can anyone help me correcting this below code to get expected output?

Check my example as below:

List<List<string>> input2 = new List<List<string>>()
    {
        new List<string>(){ "k", "B", "C" },
        new List<string>(){ "A", "B", "E"}
    };

public static List<string> LongestCommonSubsequence(List<List<string>> paths )
        {
            if (paths == null || paths.Count == 0)
            {
                return new List<string>();
            }

            int n = paths[0].Count;
            int m = paths.Count;

            int[,] L = new int[n + 1, m + 1];

            // Initialize the first row and column of the array with 0's
            for (int i = 0; i <= n; i++)
            {
                L[i, 0] = 0;
            }
            for (int j = 0; j <= m; j++)
            {
                L[0, j] = 0;
            }

            // Fill in the array using dynamic programming
            for (int i = 1; i <= n; i++)
            {
                for (int j = 1; j <= m; j++)
                {
                    if (paths[j - 1].Contains(paths[0][i - 1]))
                    {
                        L[i, j] = L[i - 1, j - 1] + 1;
                    }
                    else
                    {
                        L[i, j] = Math.Max(L[i - 1, j], L[i, j - 1]);
                    }
                }
            }

            // Backtrack to find the longest common subsequence
            int index = L[n, m];
            string[] resultArr = new string[index];
            int iIndex = n, jIndex = m;

            while (iIndex > 0 && jIndex > 0)
            {
                if (paths[jIndex - 1].Contains(paths[0][iIndex - 1]))
                {
                    resultArr[index - 1] = paths[0][iIndex - 1];
                    index--;
                    iIndex--;
                    jIndex--;
                }
                else if (L[iIndex - 1, jIndex] > L[iIndex, jIndex - 1])
                {
                    iIndex--;
                }
                else
                {
                    jIndex--;
                }
            }
            return resultArr.ToList();
        }

Thanks in advance

1

There are 1 answers

2
TheMoroccan On

you can use intersect in Linq:

int[] id1 = { 44, 26, 92, 30, 71, 38 };
int[] id2 = { 39, 59, 83, 47, 26, 4, 30 };

IEnumerable<int> both = id1.Intersect(id2);

foreach (int id in both)
 Console.WriteLine(id);

/*
This code produces the following output:

26
30
*/