Rearrange an array such that product of every two consecutive elements is a multiple of 4 | Java program to rearray array elements such that the product of every two consecutive elements is a multiple of ; 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
import java . io . * ; import java . util . * ; class GFG { public static void Permute ( Vector < Integer > arr , int n ) { int odd = 0 , four = 0 ; int non_four = 0 ; Vector < Integer > ODD = new Vector < Integer > ( ) ; Vector < Integer > FOUR = new Vector < Integer > ( n ) ; Vector < Integer > NON_FOUR = new Vector < Integer > ( n ) ; for ( int x : arr ) { if ( x % 2 != 0 ) { odd ++ ; ODD . add ( x ) ; } else if ( x % 4 == 0 ) { four ++ ; FOUR . add ( x ) ; } else { non_four ++ ; NON_FOUR . add ( x ) ; } } if ( non_four == 0 && four >= odd - 1 ) { int x = ODD . size ( ) ; int y = FOUR . size ( ) ; int i ; for ( i = 0 ; i < x ; i ++ ) { System . out . print ( ODD . get ( i ) + " ▁ " ) ; if ( i < y ) System . out . print ( FOUR . get ( i ) + " ▁ " ) ; } while ( i < y ) System . out . print ( FOUR . get ( i ) + " ▁ " ) ; System . out . println ( ) ; } else if ( non_four > 0 && four >= odd ) { int x = ODD . size ( ) ; int y = FOUR . size ( ) ; int i ; for ( i = 0 ; i < x ; i ++ ) { System . out . print ( ODD . get ( i ) + " ▁ " ) ; if ( i < y ) System . out . print ( FOUR . get ( i ) + " ▁ " ) ; } while ( i < y ) System . out . print ( FOUR . get ( i ) + " ▁ " ) ; for ( int j = 0 ; j < ( int ) NON_FOUR . size ( ) ; j ++ ) System . out . print ( NON_FOUR . get ( j ) + " ▁ " ) ; System . out . println ( ) ; } else System . out . println ( " Not ▁ Possible " ) ; } public static void main ( String [ ] args ) { Vector < Integer > arr = new Vector < Integer > ( ) ; arr . add ( 2 ) ; arr . add ( 7 ) ; arr . add ( 1 ) ; arr . add ( 8 ) ; arr . add ( 2 ) ; arr . add ( 8 ) ; Permute ( arr , arr . size ( ) ) ; } }