Need help with making a function, not sure why it won't work

May 10, 2016 at 12:18am
I am supposed to make a function that does the following:

If a1 has n1 elements in nondecreasing order, and a2 has n2 elements in nondecreasing order, place in result all the elements of a1 and a2, arranged in nondecreasing order, and return the number of elements so placed. Return −1 if the result would have more than max elements or if a1 and/or a2 are not in nondecreasing order. (Note: nondecreasing order means that no item is > the one that follows it.)

Here is my attempt and I have no idea why it won't work
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
35
36
37
38
39
40
41


#include <iostream>
#include <string>
#include <cassert>

using namespace std;

int mingle(const string a1[], int n1, const string a2[], int n2,
	string result[], int max)
{
	int j = 0;
	int m = 0;
	for (int i = 0; i < n1 - 1; i++)
	{
		if (a1[i] > a1[i + 1])
			return -1;
	}
	for (int i = 0; i < n2 - 1; i++)
	{
		if (a2[i] > a2[i + 1])
			return -1;
	}
	if (n1 + n2 > max)
		return -1;
	for (int k = 0; k < n1 + n2; k++)
	{
		if (n1 > m && n2 > j)
		{
			if (a1[m] < a2[j])
			{
				result[k] = a1[m]; m++;
			}
			else { result[k] = a2[j]; j++; }
		}
		if ((n1 = m) && (n2 > j)) { result[k] = a2[j]; j++; }
		if ((n1 > m) && (n2 = j)) { result[k] = a1[m]; m++; }
		if ((n1 = m) && (n2 = j)) break;
	}
	return n1 + n2;
}
May 10, 2016 at 2:14am
Remember that == compares two variables while = is only the assignment operator, no matter inside an if or not. Check lines 36 though to 38.
May 10, 2016 at 2:17am
Oh yeah and why are you using the string class at all? Aren't a1, a2 and result arrays of ints?
May 10, 2016 at 4:22pm
I think all you need do is change the assignment operator (=) to a comparison (==) in the lines indicated by Tyler.

@Tyler, been having too much coffee huh? The arrays are string[].
May 10, 2016 at 9:07pm
@tipaye What do you mean... If the arrays are string[] how can we say that it's in "non-decreasing order"? How can you compare two strings to see which one is "more"? I don't think that the ">" and "<" operators are overloaded for strings.
May 25, 2016 at 4:49pm
@Tyler
The usual comparison operators (non-member) are all available for string.

operator==
operator!=
operator<
operator>
operator<=
operator>=

Happy coding.
Topic archived. No new replies allowed.