Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

Counting Pairs in an Array, resulting in a given sum

<script>
/* javascript implementation of simple method to find count of
pairs with given sum*/
    var arr = [ 1, 5, 7, -1, 5 ];
 
    // Returns number of pairs in arr[0..n-1] with sum equal
    // to 'sum'
    function getPairsCount(n , sum) {
        var hm = new Map();
 
        // Store counts of all elements in map hm
        for (var i = 0; i < n; i++) {
 
            // initializing value to 0, if key not found
            if (!hm.has(arr[i]))
                hm.set(arr[i], 0);
 
            hm.set(arr[i], hm.get(arr[i]) + 1);
        }
        var twice_count = 0;
 
        // iterate through each element and increment the
        // count (Notice that every pair is counted twice)
        for (i = 0; i < n; i++) {
            if (hm.get(sum - arr[i]) != null)
                twice_count += hm.get(sum - arr[i]);
 
            // if (arr[i], arr[i]) pair satisfies the
            // condition, then we need to ensure that the
            // count is decreased by one such that the
            // (arr[i], arr[i]) pair is not considered
            if (sum - arr[i] == arr[i])
                twice_count--;
        }
 
        // return the half of twice_count
        return twice_count / 2;
    }
 
    // Driver method to test the above function
        var sum = 6;
        document.write("Count of pairs is " + getPairsCount(arr.length, sum));
 
// This code is contributed by umadevi9616
</script>
Source by www.geeksforgeeks.org #
 
PREVIOUS NEXT
Tagged: #Counting #Pairs #resulting #sum
ADD COMMENT
Topic
Name
8+3 =