Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Given an array arr, find element pairs whose sum equal the second argument arg and return the sum of their indices. If multiple pairs are possible that have the same numeric elements but different indices, return the smallest sum of indices. Once an element has been used, it cannot be reused to pair with another. For example pairwise([7, 9, 11, …
function pairwise(arr, arg) {
//if its an empty array return 0
if(arr.length === 0){
return 0;
}
//reduce the array by looping over the array and checking if the
//sum of the current element and another element = the argument.
//if they match and the indexes of both are different, add the indexes to
//the output array.
var pairs = arr.reduce(function(accum, curr, index, array){
for(var i = 0; i<array.length; i++){
if(curr + array[i] === arg && index !== i){
if(!accum.includes(index) && !accum.includes(i)){
accum.push(index, i);
}
}
}
return accum;
}, []);
//reduce the new array to single number by adding them all up
return pairs.reduce(function(x, el){
return x + el;
});
}
pairwise([1,1,1], 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.