- Related Questions & Answers
- Finding the difference between two arrays - JavaScript
- How to get the difference between two arrays in JavaScript?
- Find difference between sums of two diagonals in C++.
- Find minimum difference between any two element in C++
- Find the difference between two datetime values with MySQL?
- How to find common elements between two Arrays using STL in C++?
- Find the difference between two timestamps in days with MySQL
- Find the closest pair from two sorted arrays in c++
- How to find the common elements between two or more arrays in JavaScript?
- C# difference in milliseconds between two DateTime
- Find relative complement of two sorted arrays in C++
- Find the minimum distance between two numbers in C++
- Find the minimum difference between Shifted tables of two numbers in Python
- C# program to list the difference between two lists
- C# Program to get the difference between two dates

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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]

#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); }

Compatibility difference: 2

Advertisements