Find the compatibility difference between two arrays in C++

C++Server Side ProgrammingProgramming

Consider there are two friends and now they want to test their bonding. So they will check, how much compatible they are. Given the numbers n, numbered from 1..n. And they are asked to rank the numbers. They have to find the compatibility difference between them. The compatibility difference is basically the number of mismatches in the relative ranking of the same movie given by them. So if A = [3, 1, 2, 4, 5], and B = [3, 2, 4, 1, 5], then the output will be 2. The compatibility difference is 2, as first ranks movie 1 before 2 and 4, but other ranks it after.

To solve this, we will traverse both arrays, when the current elements are same, then do nothing. Then find the next position of A and B, let the position be j, one by one move B[j] to B[i]

Example

Live Demo

#include<iostream>
using namespace std;

int getArrayDiff(int A[], int B[], int n) {
int result = 0;

for (int i = 0; i < n; i++) {
if (A[i] != B[i]) {

int j = i + 1;
while (A[i] != B[j])
j++;

while (j != i) {
swap(B[j], B[j - 1]);
j--;
result++;
}
}
}
return result;
}

int main() {
int A[] = { 3, 1, 2, 4, 5 };
int B[] = { 3, 2, 4, 1, 5 };
int n = sizeof(A)/sizeof(A[0]);

cout << "Compatibility difference: " << getArrayDiff(A, B, n);
}



Output

Compatibility difference: 2
Published on 30-Dec-2019 09:50:39