HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

Given an array of integers, return all pairs that add up to 100

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
pairsallarrayreturn100thatintegersgivenadd

Problem

I was recently given this programming challenge on an interview, and I decided to use javascript to solve it. I did, but I'm not happy with my implementation. I can't help thinking there must be a better way of doing this.

The exercise goes like this:


Given an array of integers, write a function that returns an array of
each pair of integers that add up to 100. The input is



[0, 1, 100, 99, 0, 10, 90, 30, 55, 33, 55, 75, 50, 51, 49, 50, 51, 49, 51]



and the function should return something like this (the order is not
important).



[ [0,100], [1,99], [10,90], [50,50], [49,51] ]


My implementation looks like this, is there a different approach out there?

var sample_data = [0, 1, 100, 99, 0, 10, 90, 30, 55, 33, 55, 75, 50, 51, 49, 50, 51, 49, 51]

function process(data){

    var result = []
    var a;
    var b;

    for (var i=0; i < data.length; i++) {

        a = data[i];

        for (var j=0; j < data.length; j++) {

            b = data[j]

            if ( (parseInt(a) + parseInt(b)) === 100 && result.indexOf(a+","+b) == -1 && result.indexOf(b+","+a ) == -1 ) {
               result.push( a+","+b )
            }

        }    
    }

    for (var i=0; i < result.length; i++) {
        result[i] = result[i].split(',')
    }

    return result
} 

process(sample_data);

Solution

okay, my javascript is not great but this should find all pairs in a single pass.

this assumes all values are between 0 and 100, like in the question.

Here is a working JSFiddle that shows the code in action.

var sample_data = [0, 1, 100, 99, 0, 10, 90, 30, 55, 33, 55, 75, 50, 51,
                      49, 50, 51, 49, 51];

var found = {};
var results = [];
for(var i of sample_data) {
    if (found[100 - i] === true) {
        // pair found
        results.push({
            a: i,
            b: 100 - i
        });
    }

    found[i] = true;
}


essentially, found is used as a hashset to see if the required reciprocal has already occurred in the array.

This makes the code more concise while being as easy to understand, therefore more maintainable. The code is also likely to have superior performance to code with nested loops.

Code Snippets

var sample_data = [0, 1, 100, 99, 0, 10, 90, 30, 55, 33, 55, 75, 50, 51,
                      49, 50, 51, 49, 51];

var found = {};
var results = [];
for(var i of sample_data) {
    if (found[100 - i] === true) {
        // pair found
        results.push({
            a: i,
            b: 100 - i
        });
    }

    found[i] = true;
}

Context

StackExchange Code Review Q#74152, answer score: 13

Revisions (0)

No revisions yet.