Count quadruplets with sum K from given array | Function to return the number of quadruplets having given sum ; Initialize variables ; Initialize answer ; All possible first elements ; All possible second element ; Use map to find the fourth element ; All possible third elements ; Calculate number of valid 4 th elements ; Update the twice_count ; Unordered pairs ; Return answer ; Given array arr [ ] ; Given sum S ; Function Call
function countSum ( a , n , sum ) { var i , j , k , l ; var count = 0 ; for ( i = 0 ; i < n - 3 ; i ++ ) { for ( j = i + 1 ; j < n - 2 ; j ++ ) { var req = sum - a [ i ] - a [ j ] ; var m = new Map ( ) ; for ( k = j + 1 ; k < n ; k ++ ) { if ( m . has ( a [ k ] ) ) m . set ( a [ k ] , m . get ( a [ k ] ) + 1 ) else m . set ( a [ k ] , 1 ) } var twice_count = 0 ; for ( k = j + 1 ; k < n ; k ++ ) { if ( m . has ( req - a [ k ] ) ) twice_count += m . get ( req - a [ k ] ) ; if ( ( req - a [ k ] ) == a [ k ] ) twice_count -- ; } count += parseInt ( twice_count / 2 ) ; } } return count ; } var arr = [ 4 , 5 , 3 , 1 , 2 , 4 ] ; var S = 13 ; var N = arr . length ; document . write ( countSum ( arr , N , S ) ) ;