- #1
chiurox
- 35
- 0
Homework Statement
OK, so in this CS project, we need to make functions for arrays.
I need to implement a function that does the following:
int subsequence(const string a1[], int n1, const string a2[], int n2);
If all n2 elements of a2 appear in a1, consecutively and in the same order, then return the position in a1 where that subsequence begins. If the subsequence appears more than once in a1, return the smallest such beginning position. Return −1 if a1 does not contain a2 as a continguous subsequence. For example,
string big[10] = { "a", "b", "c", "d", "e" };
string little1[10] = { "b", "c", "d" };
int k = subsequence(big, 5, little1, 3); // returns 1
string little2[10] = { "c", "e" };
int m = subsequence(big, 5, little2, 2); // returns -1
The Attempt at a Solution
So far what I have is this:
int subsequence(const string a1[], int n1, const string a2[], int n2)
{
if (n1 < 0 || n2 < 0) return -1;
int k2 = 0;
//traverse a1, marking off items of a2
for (int k1 = 0; k1 < n1 && k2 < n2; k1++)
{
if (a1[k1] == a2[k2])
{
k2++;
cout << "K2: " << k2 << "N2: " << n2 << endl;
}
}
return k2-n2+1;
}
My code works for the first example, but not the second one.