I am trying to create an algorithm that determines if one array list (s1) is a sub-sequence of another array list (s2). The elements in the first list all need to be in the second list and must be in the same order. So s1 is a sub-sequence of s2, but s1 is not a sub-sequence of s2. I need to use iterators to go through each list, and I should only go through each list once (since it has to be in the same order). I seem to have an issue with the next() becoming void ?? What would cause this/how can I fix this? The code I currently have seems to work as I would hope with the exception of not going to the next element in the first array list.
import dataStructures.*;
public class Subsequence2
{
public static void main(String[] args)
{
ArrayList<Character> s1 = new ArrayList<Character>();
s1.add('n');
s1.add('p');
s1.add('a');
ArrayList<Character> s2 = new ArrayList<Character>();
s2.add('a');
s2.add('n');
s2.add('b');
s2.add('p');
s2.add('c');
s2.add('a');
Subsequence2 one = new Subsequence2();
System.out.print("S1 is a subsequence of S2 is a ");
System.out.print(one.subSequence(s1, s2));
System.out.print(" statment.");
} //end main
public static <T> boolean subSequence(ArrayList<T> s1, ArrayList<T> s2)
{
//if s1 is empty or if s1 and s2 are empty it is a subsequence
if(s1.isEmpty() || (s1.isEmpty() && s2.isEmpty()))
{
return true;
}
//if s2 is empty and s1 is not is is not a subsequence.
else if(s2.isEmpty())
{
return false;
}
else
{
int s1Count = 0; //count items matched
Iterator<T> itr1 = s1.iterator();
Iterator<T> itr2 = s2.iterator();
while(itr1.hasNext())
//for(Iterator<T> itr1 = s1.iterator(); itr1.hasNext();) //traverse s1
{
T c1 = itr1.getCurrent();
itr1.next(); //go to next element of s1
while(itr2.hasNext()) //traverse s2
{
T c2 = itr2.getCurrent();
//if items are equal check the next item and add 1 to count of items matched
if(c1.equals(c2))
{
itr2.next();
++s1Count;
//used for testing- just want to see what index it is pulling
System.out.print("s1 index " + s1.indexOf(c1) + " s2 index " + s2.indexOf(c2) + " \n" + c1 + " " + c2 + "\n");
}
//if it didn't match, check next element
else
{
itr2.next();
}
if(s1Count == s1.size()) //if match count is == to s1 size, it is a subsequence
{
return true;
}
} // end itr2 while
} //end for itr1
} //end else not empty
return false;
} //end subSequence method
}//end class
if(s1.isEmpty() || (s1.isEmpty() && s2.isEmpty())is equivalent to justif(s1.isEmpty()). Ifs1is empty, the whole condition short-circuits totrue(without the|| (s1.isEmpty() & s2.isEmpty())bit even being evaluated). Ifs1is not empty, then that second part will be evaluated, but will always evaluate tofalsesince it's essentially(false && s2.isEmpty())(since we know thats1.isEmpty()is false).