Check if elements of an array can be arranged satisfying the given condition | Function to return true if the elements can be arranged in the desired order ; If 2 * x is not found to pair ; Remove an occurrence of x and an occurrence of 2 * x ; Driver Code ; Function call to print required answer
function canReorder ( A , n ) { let m = new Map ( ) ; for ( let i = 0 ; i < n ; i ++ ) { if ( m . has ( A [ i ] ) ) { m . set ( A [ i ] , m . get ( A [ i ] ) + 1 ) } else { m . set ( A [ i ] , 1 ) } } A . sort ( ( a , b ) => a - b ) ; let count = 0 ; for ( let i = 0 ; i < n ; i ++ ) { if ( m . get ( A [ i ] ) == 0 ) continue ; if ( m . get ( 2 * A [ i ] ) ) { count += 2 ; m . set ( A [ i ] , m . get ( A [ i ] ) - 1 ) ; m . set ( 2 * A [ i ] , m . get ( 2 * A [ i ] ) - 1 ) ; } } if ( count == n ) return " " ; else return " " ; } let A = [ 4 , - 2 , 2 , - 4 ] ; let n = A . length ; document . write ( ( canReorder ( A , n ) ) ) ;