Help with array function please! Not sure why it won't work

I am supposed to make a function that can do the following:

function: bool subsequence(const string a1[], int n1, const string a2[], int n2)

Task:
If all n2 elements of a2 appear in a1, in the same order (though not necessarily consecutively), then return true. Return false if a1 does not contain a2 as a subsequence. (Of course, the empty sequence is a subsequence of any sequence.) Return false if this function is passed any bad arguments.

Here is what I tried and I have no idea why it won't work. Any help is appreciated!

code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <string>


using namespace std;

bool subsequence(const string a1[], int n1, const string a2[], int n2)
{
	if (n1 < 0 || n2 < 0 || n2 > n1) { 
	return false;
}

	else if (n2 == 0) {
	return true;
}


for (int i = 0; i < n1; i++) { 
	if (a1[i] == a2[0]) 
	{
		int j = 0;
			for (int k = 0; k + i < n1; k++)
			{
				if (a1[i + k] == a2[j])
				{
					j++; 
					if (j = n2) 
						return true;
				}
			}
		}
}
return false;
}



It runs fine it just gives true on many cases when it should give false.




edit: fixed formatting
Last edited on
Please use code tags and indentation when you post code - it makes it a lot easier to read.

What are the test cases?

Something definitely looks off with the last if statement, which is assigning, not comparing.


Sorry about the formatting. Wasn't sure how to work it.

A test case it fails on is
string h[7] = {"1" , "2", "3", "4", "5", "6", "7"}
string g[4] = {"1", "2", "cat", "6"}
bool subsequence(h, 7, g, 4)
Last edited on
Use of code tags, see http://www.cplusplus.com/articles/jEywvCM9/

The std::includes does similar (but not exactly same) operation. See http://www.cplusplus.com/reference/algorithm/includes/
Topic archived. No new replies allowed.