
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Compatibility Difference Between Two Arrays in C++
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
#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