
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Find the 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
- Related Articles
- Find the Symmetric difference between two arrays - JavaScript
- How to find set difference between two Numpy arrays?
- Finding the difference between two arrays - JavaScript
- How to get the difference between two arrays in JavaScript?
- How to find intersection between two Numpy arrays?
- How to find the common elements between two or more arrays in JavaScript?
- Python Pandas – Find the Difference between two Dataframes
- Difference between Arrays and Collection in Java
- Difference Between Matrices and Arrays in Python?
- Find the difference between two timestamps in days with MySQL
- How to find common elements between two Arrays using STL in C++?
- Find the difference between two datetime values with MySQL?
- Find difference between sums of two diagonals in C++.
- Find minimum difference between any two element in C++
- Python program to find difference between two timestamps
