Created
August 29, 2019 15:12
-
-
Save PartyLich/50ad6f87db5f7449c369b1911988eb4f to your computer and use it in GitHub Desktop.
FreeCodeCamp => Algorithms: Pairwise
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
/** | |
* @param {number} prev | |
* @param {number} next | |
* @return {number} the sum of prev and next | |
*/ | |
const add = (prev, next) => prev + next; | |
/** | |
* Generate index pair combinations, arr.length choose 2 | |
* @param {array} arr | |
* @return {array} new array containing each index pair combination | |
* as a subarray | |
*/ | |
const getIndexCombos = (arr) => { | |
let res = []; | |
arr.forEach((val, index) => { | |
let pairs = []; | |
for (let i = index + 1, len = arr.length; i < len; i++) { | |
pairs.push([index, i]); | |
} | |
res = res.concat(pairs); | |
}); | |
return res; | |
}; | |
/** | |
* @param {array} arr | |
* @param {number} sum | |
* @return {number} sum of arr indices such that the arr element pairs sum equal | |
* the sum parameter | |
*/ | |
function pairwise(arr, arg) { | |
if (!arr.length) return 0; | |
// Generate combinations, arr.length choose 2 | |
const combinations = getIndexCombos(arr) | |
// get sum of each combo | |
.map((val, ind) => ({ | |
sum: arr[val[0]] + arr[val[1]], | |
pair: val, | |
})); | |
let usedIndex = new Set(); | |
let sums = combinations | |
.filter((val) => { | |
// filter to match arg | |
if (val.sum !== arg) return false; | |
// then filter index re-use | |
if (usedIndex.has(val.pair[0])) return false; | |
if (usedIndex.has(val.pair[1])) return false; | |
usedIndex.add(val.pair[0]); | |
usedIndex.add(val.pair[1]); | |
return true; | |
}) | |
.map((val) => | |
// sum indices in each pair | |
val.pair.reduce(add) | |
); | |
return sums.reduce(add); | |
} | |
pairwise([1, 4, 2, 3, 0, 5], 7); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment