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 . get ( i ) and FOUR . get ( i ) consecutively ; Print the remaining FOUR . get ( i ) , if any ; Condition for rearrangement to be possible ; Print ODD . get ( i ) and FOUR . get ( i ) consecutively ; Print the remaining FOUR . get ( i ) , if any ; Print the NON_FOUR . get ( i ) elements at the end ; No possible configuration ; Driver Code
function Permute ( arr , n ) { let odd = 0 , four = 0 ; let non_four = 0 ; let ODD = [ ] ; let FOUR = [ ] ; let NON_FOUR = [ ] ; for ( let x = 0 ; x < arr . length ; x ++ ) { if ( arr [ x ] % 2 != 0 ) { odd ++ ; ODD . push ( arr [ x ] ) ; } else if ( arr [ x ] % 4 == 0 ) { four ++ ; FOUR . push ( arr [ x ] ) ; } else { non_four ++ ; NON_FOUR . push ( arr [ x ] ) ; } } if ( non_four == 0 && four >= odd - 1 ) { let x = ODD . length ; let y = FOUR . length ; let i ; for ( i = 0 ; i < x ; i ++ ) { document . write ( ODD [ i ] + " " ) ; if ( i < y ) document . write ( FOUR [ i ] + " " ) ; } while ( i < y ) document . write ( FOUR [ i ] + " " ) ; document . write ( " " ) ; } else if ( non_four > 0 && four >= odd ) { let x = ODD . length ; let y = FOUR . length ; let i ; for ( i = 0 ; i < x ; i ++ ) { document . write ( ODD [ i ] + " " ) ; if ( i < y ) document . write ( FOUR [ i ] + " " ) ; } while ( i < y ) document . write ( FOUR [ i ] + " " ) ; for ( let j = 0 ; j < NON_FOUR . length ; j ++ ) document . write ( NON_FOUR [ j ] + " " ) ; document . write ( " " ) ; } else document . write ( " " ) ; } let arr = [ 2 , 7 , 1 , 8 , 2 , 8 ] Permute ( arr , arr . length ) ;