Rearrange an array such that 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
def Permute ( arr , n ) : NEW_LINE INDENT odd = 0 NEW_LINE four = 0 NEW_LINE non_four = 0 NEW_LINE ODD , FOUR , NON_FOUR = [ ] , [ ] , [ ] NEW_LINE for x in arr : NEW_LINE INDENT if ( x & 1 ) : NEW_LINE INDENT odd += 1 NEW_LINE ODD . append ( x ) NEW_LINE DEDENT elif ( x % 4 == 0 ) : NEW_LINE INDENT four += 1 NEW_LINE FOUR . append ( x ) NEW_LINE DEDENT else : NEW_LINE INDENT non_four += 1 NEW_LINE NON_FOUR . append ( x ) NEW_LINE DEDENT DEDENT if ( non_four == 0 and four >= odd - 1 ) : NEW_LINE INDENT x = len ( ODD ) NEW_LINE y = len ( FOUR ) NEW_LINE i = 0 NEW_LINE while i < x : NEW_LINE INDENT print ( ODD [ i ] , end = " ▁ " ) NEW_LINE if ( i < y ) : NEW_LINE INDENT print ( FOUR [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT while ( i < y ) : NEW_LINE INDENT print ( FOUR [ i ] , end = " ▁ " ) NEW_LINE i += 1 NEW_LINE DEDENT print ( ) NEW_LINE DEDENT elif ( non_four > 0 and four >= odd ) : NEW_LINE INDENT x = len ( ODD ) NEW_LINE y = len ( FOUR ) NEW_LINE i = 0 NEW_LINE while i < x : NEW_LINE INDENT print ( ODD [ i ] , end = " ▁ " ) NEW_LINE if ( i < y ) : NEW_LINE INDENT print ( FOUR [ i ] , end = " ▁ " ) NEW_LINE DEDENT i += 1 NEW_LINE DEDENT while ( i < y ) : NEW_LINE INDENT print ( FOUR [ i ] , end = " ▁ " ) NEW_LINE i += 1 NEW_LINE DEDENT for j in NON_FOUR : NEW_LINE INDENT print ( j , end = " ▁ " ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( " Not ▁ Possible " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 7 , 1 , 8 , 2 , 8 ] NEW_LINE N = len ( arr ) NEW_LINE Permute ( arr , N ) NEW_LINE DEDENT