Created
April 17, 2018 19:01
-
-
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, …
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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