Member-only story
In C++, write a method called findDifference that returns the position of the first corresponding elements of two arrays that are not equal.
Question
int findDifference(const string a1[], int n1, const string a2[], int n2);
Return the position of the first corresponding elements of a1
and a2
that are not equal. n1
is the number of interesting elements in a1
, and n2
is the number of interesting elements in a2
. If the arrays are equal up to the point where one or both runs out, return whichever value of n1
and n2
is less than or equal to the other. Here's an example:
string people[5] = { "juliet", "sierra", "sal", "echo", "november" };
string bench[6] = { "juliet", "sierra", "charlie", "echo", "november", "samuel" };
int r = findDifference(people, 5, bench, 6); // returns 2
int s = findDifference(people, 2, bench, 1); // returns 1
Solution
int findDifference(const string a1[], int n1, const string a2[], int n2){int findDifferencePosition=-1;for (unsigned int i=0; i<n1; i++){if (i <= n2){if (a1[i]!=a2[i]){findDifferencePosition=i;break;}}}return findDifferencePosition;}
Explanation
First check if i is less than n2 to prevent an out of bounds error. Then check if the current letter in the a1 array is not equal to the current letter in the a2 array. Once a mismatch is found, update the findDifferencePosition variable to the position where the difference was found. After the for loop has finished, findDifferencePosition will be returned, and that variable will be the last position found before a difference was found.