Double for loop not working in Java
import java.io.File;
import java.util.Scanner;
public class LongestCommonSubsequence {
public static void main(String []args){
Scanner input=null;
String x=null;
String y=null;
int M;
int N;
int [] x_marker;
int [][] lcs;
try{
input=new Scanner(new File(args[0]));
while(input.hasNext()){
String[] strs= input.nextLine().split(";");
x=strs[0];
y=strs[1];
M=x.length();
N=y.length();
x_marker=new int[M];
lcs=new int[M+1][N+1];
/*Initialize the first row and col of lcs matrix*/
for(int i=0;i<=M;i++)lcs[i][0]=0;
for(int i=0;i<=N;i++)lcs[0][i]=0;
System.out.println("M "+M);
System.out.println("N "+N);
for(i=1;i<=M;i++){
for(int j=1;j<=N;j++){
if(x.charAt(i)==y.charAt(j)){
x_marker[i]=1;
lcs[i][j]=1+lcs[i-1][j-1];
}else {
int l=lcs[i-1][j];
int r=lcs[i][j-1];
if(l<r)lcs[i][j]=r;
else lcs[i][j]=l;
}
}
}
System.out.println("Length of LCS is "+lcs[M][N]);
}
}catch(Exception e){
}
}
}
This is the code for finding Longest common subsequence. Strings are read
from input file. Two strings per line seperated by ";" The outer for loop
executes only once, though i and M are correct.
No comments:
Post a Comment