I have the following code, which does not work correctly for some reason that I am trying to figure out:
public static int score(String gene1, String gene2){
char[] a=new char[gene1.length()];
char[] b=new char[gene2.length()];
a=gene1.toCharArray();
b=gene2.toCharArray();
return score(a, b, 0,0);
}
private static int score(char[] a, char[] b, int i, int j){
if(a[i]=='\0' || b[j]=='\0')
return 0;
else if (a[i]==b[j])
return 1+score(a, b, i+1, j+1);
else
return max(score(a, b,i+1, j),score(a, b, i, j+1));
}
private static int max (int a, int b){
if (a<b) return b;
else return a;
}
Here is where it fails:
assertEquals(2, GeneAnalysis.score("ACGT","AC"));
I get an IndexOutofBoundsError
Any ideas? Also, when offering help, please do not change method parameters. They are supposed to be the way they are.
Part of this seems to be a confusion between C and Java….
C has a null terminator for strings, Java does not. Instead to check for the end of a Java array you will need to use the .length attribute… something like:
Edit based on comment.
Really, you should ask a separate question on this… but here is a stab at how it works. First off you are using recursion, which, yes, is a tricky concept. Wikipedia probably can help you with the basics of recursion.
Here is the code closer to how I would write it, with comments showing you the order that things occur in: