Count valid pairs in the array satisfying given conditions | Function to return total valid pairs ; Initialize count of all the elements ; frequency count of all the elements ; Add total valid pairs ; Exclude pairs made with a single element i . e . ( x , x ) ; Driver Code ; Function call to prvar required answer
function ValidPairs ( arr , n ) { var count = Array ( 121 ) . fill ( 0 ) ; for ( i = 0 ; i < n ; i ++ ) count [ arr [ i ] ] += 1 ; var ans = 0 ; for ( i = 0 ; i < n ; i ++ ) for ( j = 0 ; j < n ; j ++ ) { if ( arr [ i ] < arr [ j ] ) continue ; if ( Math . abs ( arr [ i ] - arr [ j ] ) % 2 == 1 ) continue ; ans += count [ arr [ i ] ] * count [ arr [ j ] ] ; if ( arr [ i ] == arr [ j ] ) ans -= count [ arr [ i ] ] ; } return ans ; } var arr = [ 16 , 17 , 18 ] ; var n = arr . length ; document . write ( ValidPairs ( arr , n ) ) ;