Distinct adjacent elements in an array | JavaScript program to check if we can make neighbors distinct . ; map used to count the frequency of each element occurring in the array ; In this loop we count the frequency of element through map m . ; mx store the frequency of element which occurs most in array . ; In this loop we calculate the maximum frequency and store it in variable mx . ; By swapping we can adjust array only when the frequency of the element which occurs most is less than or equal to ( n + 1 ) / 2 . ; Driver program to test the above function
function distinctAdjacentElement ( a , n ) { let m = new Map ( ) ; for ( let i = 0 ; i < n ; ++ i ) { m [ a [ i ] ] ++ ; if ( m . has ( a [ i ] ) ) { m . set ( a [ i ] , m . get ( a [ i ] ) + 1 ) } else { m . set ( a [ i ] , 1 ) } } let mx = 0 ; for ( let i = 0 ; i < n ; ++ i ) if ( mx < m . get ( a [ i ] ) ) mx = m . get ( a [ i ] ) ; if ( mx > Math . floor ( ( n + 1 ) / 2 ) ) document . write ( " " + " " ) ; else document . write ( " " ) ; } let a = [ 7 , 7 , 7 , 7 ] ; let n = a . length ; distinctAdjacentElement ( a , n ) ;