Rearrange an array such that product of every two consecutive elements is a multiple of 4 | C ++ Program to rearray array elements such that the product of every two consecutive elements is a multiple of 4 ; Function to rearrange array elements such that the every two consecutive elements is a multiple of 4 ; If element is odd ; Odd ; If element is divisible by 4 ; Divisible by 4 ; If element is not divisible by 4 ; Even but not divisible by 4 ; Condition for rearrangement to be possible ; Print ODD [ i ] and FOUR [ i ] consecutively ; Print the remaining FOUR [ i ] , if any ; Condition for rearrangement to be possible ; Print ODD [ i ] and FOUR [ i ] consecutively ; Print the remaining FOUR [ i ] , if any ; Print the NON_FOUR [ i ] elements at the end ; No possible configuration ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void Permute ( vector < int > & arr , int n ) { int odd = 0 , four = 0 ; int non_four = 0 ; vector < int > ODD , FOUR , NON_FOUR ; for ( auto x : arr ) { if ( x & 1 ) { odd ++ ; ODD . push_back ( x ) ; } else if ( x % 4 == 0 ) { four ++ ; FOUR . push_back ( x ) ; } else { non_four ++ ; NON_FOUR . push_back ( x ) ; } } if ( non_four == 0 && four >= odd - 1 ) { int x = ODD . size ( ) ; int y = FOUR . size ( ) ; int i ; for ( i = 0 ; i < x ; i ++ ) { cout << ODD [ i ] << " ▁ " ; if ( i < y ) cout << FOUR [ i ] << " ▁ " ; } while ( i < y ) cout << FOUR [ i ] << " ▁ " ; cout << endl ; } else if ( non_four > 0 and four >= odd ) { int x = ODD . size ( ) ; int y = FOUR . size ( ) ; int i ; for ( i = 0 ; i < x ; i ++ ) { cout << ODD [ i ] << " ▁ " ; if ( i < y ) cout << FOUR [ i ] << " ▁ " ; } while ( i < y ) cout << FOUR [ i ] << " ▁ " ; for ( int j = 0 ; j < ( int ) NON_FOUR . size ( ) ; j ++ ) cout << NON_FOUR [ j ] << " ▁ " ; cout << endl ; } else cout << " Not ▁ Possible " << endl ; } signed main ( ) { vector < int > arr = { 2 , 7 , 1 , 8 , 2 , 8 } ; int N = sizeof ( arr ) / sizeof ( arr ) ; Permute ( arr , N ) ; return 0 ; }