Sunday 22 March 2015

Write a program to find length of Longest Common Subsequence(LCS) in two strings using dynamic programming.

#include<stdio.h>
#include<string.h>
void lcs(char*, char*, int, int);
int smax(int, int);
int array[51][51];
int main()
{
char a[50],b[50];
int m,n;
printf("Enter the first sequence \n");
scanf("%s",a);
m=strlen(a);
printf("Enter the second one\n");
scanf("%s",b);
n=strlen(b);
lcs(a,b,m,n);
printf("%d",array[m][n]);
    return 0;
}
void lcs(char *a, char *b,int m , int n)
{
    int i,j;
    for(i=0;i<m;i++)
    {
        for(j=0;j<n;j++)
        {
            if(i==0||j==0)
                array[i][j]=0;
                else if(a[i-1]==b[j-1])
                {
                    array[i][j]=1+array[i-1][j-1];
                }
                else
                {
                    array[i][j]=smax(array[i-1][j],array[i][j-1]);
                }
        }
    }
}

int smax(int a, int b)
{
    if(a>b)
        return a;
    else
        return b;

}

Output:



5 comments:

  1. Hi ..guys if you like my programs and still want some more detailed explanations of the same ..then do inform me in the comments

    ReplyDelete
  2. Please provide the elaborated algo for the code. What is the need to pass m and n in the lcs function, they are not being used there.

    ReplyDelete
  3. The for loops should have end conditions of i < m & j < n instead of using hardcoded 51 value.

    ReplyDelete
  4. hey sorry yogesh for late replying to your comment ..ya Karthikeyan you are right it should be i<m & j,n, Lately when i have written this code i was testing this for a particular dna strings of fixed and i forgetten to change it ..thanks for pointing out the mistake

    ReplyDelete
  5. hey Yogesh i will very soon update the code with explanations

    ReplyDelete