Permutation of an array that has smaller values from another array | C ++ program to find permutation of an array that has smaller values from another array ; Function to print required permutation ; Storing elements and indexes ; Filling the answer array ; pair element of A and B ; Fill the remaining elements of answer ; Output required permutation ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; void anyPermutation ( int A [ ] , int B [ ] , int n ) { vector < pair < int , int > > Ap , Bp ; for ( int i = 0 ; i < n ; i ++ ) Ap . push_back ( make_pair ( A [ i ] , i ) ) ; for ( int i = 0 ; i < n ; i ++ ) Bp . push_back ( make_pair ( B [ i ] , i ) ) ; sort ( Ap . begin ( ) , Ap . end ( ) ) ; sort ( Bp . begin ( ) , Bp . end ( ) ) ; int i = 0 , j = 0 , ans [ n ] = { 0 } ; vector < int > remain ; while ( i < n && j < n ) { if ( Ap [ i ] . first > Bp [ j ] . first ) { ans [ Bp [ j ] . second ] = Ap [ i ] . first ; i ++ ; j ++ ; } else { remain . push_back ( i ) ; i ++ ; } } j = 0 ; for ( int i = 0 ; i < n ; ++ i ) if ( ans [ i ] == 0 ) { ans [ i ] = Ap [ remain [ j ] ] . first ; j ++ ; } for ( int i = 0 ; i < n ; ++ i ) cout << ans [ i ] << " ▁ " ; } int main ( ) { int A [ ] = { 12 , 24 , 8 , 32 } ; int B [ ] = { 13 , 25 , 32 , 11 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; anyPermutation ( A , B , n ) ; return 0 ; }