Rearrange an array to make similar indexed elements different from that of another array | C ++ program for the above approach ; Function to find the arrangement of array B [ ] such that element at each index of A [ ] and B [ ] are not equal ; Print not possible , if arrays only have single equal element ; Reverse array B ; Traverse over arrays to check if there is any index where A [ i ] and B [ i ] are equal ; Swap B [ i ] with B [ i - 1 ] ; Break the loop ; Print required arrangement of array B ; Driver Code ; Given arrays A [ ] and B [ ] ; Length of array A [ ] ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void RearrangeB ( int A [ ] , vector < int > B , int n ) { if ( n == 1 && A [ 0 ] == B [ 0 ] ) { cout << " - 1" << endl ; return ; } for ( int i = 0 ; i < n / 2 ; i ++ ) { int t = B [ i ] ; B [ i ] = B [ n - i - 1 ] ; B [ n - i - 1 ] = t ; } for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( B [ i ] == A [ i ] ) { int t = B [ i + 1 ] ; B [ i + 1 ] = B [ i ] ; B [ i ] = t ; break ; } } for ( int k : B ) cout << k << " ▁ " ; } int main ( ) { int A [ ] = { 2 , 4 , 5 , 8 } ; vector < int > B = { 2 , 4 , 5 , 8 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; RearrangeB ( A , B , n ) ; }