I'm new to writing algorithms, i am making a program that checks if a string is an ordered shuffle of 2 other strings. (ordered from left to right) for example
string 1 = dog
string 2 = cat
string shuffle = dcoagt
here is my algorithm
**Algorithm: orderedSort(a,b,c)**
given strings a,b,c determine whether c is an ordered shuffle of a and b
l := length of (a + b)
if (l = 0) then
return true
if (l not = length of c)
return false
else
d := substring of a position 1 to 1
e := substring of b position 1 to 1
f := substring of c position 1 to 1
if (d = f) then
return orderedSort(a-d, b, c-f)
if (e = f) then
return orderedSort(a, b-e, c-f)
if (d and e = f) then
return orderedSort(a-d, b, c-f) or orderedSort(a, b-e, c-f)
My question is, is this correct (if not, suggestions on how to write it) as i was not sure how i would write pseudo code for the last if statement, as the recursion can go either way.
Or do i not need to write the last if statement and the programmer would include it when making the program so it doesn't fail in the case of
string 1 = aa
string 2 = aaf
string combination = aafaa
my Java implementation of this is
public class OrderedSort {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String a = "xxyxxy";
String b = "xxzxxz";
String c = "xxzxxyxxyxxz";
System.out.println(c + " is an ordered sort of " + a + " and " + b + " ... " + ordered(a,b,c));
}
public static boolean ordered(String a, String b, String c){
if(!((a.length()+b.length())==c.length()))
return false;
if(c.length()== 0)
return true;
if(a.length()>0 && b.length()>0 && a.substring(0,1).equals(b.substring(0,1)))
return ordered(a.substring(1),b,c.substring(1)) || ordered(a,b.substring(1),c.substring(1));
if(a.length()>0 && a.substring(0,1).equals(c.substring(0,1)))
return ordered(a.substring(1),b,c.substring(1));
if(b.length()>0 &&b.substring(0,1).equals(c.substring(0,1)))
return ordered(a,b.substring(1),c.substring(1));
return false;
}
}