Skip to content

Instantly share code, notes, and snippets.

@nickihastings
Created April 17, 2018 19:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickihastings/dbd3015b4042c9be44c08695138405a8 to your computer and use it in GitHub Desktop.
Save nickihastings/dbd3015b4042c9be44c08695138405a8 to your computer and use it in GitHub Desktop.
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