Skip to content

Instantly share code, notes, and snippets.

@PartyLich
Created August 29, 2019 15:12
Show Gist options
  • Save PartyLich/50ad6f87db5f7449c369b1911988eb4f to your computer and use it in GitHub Desktop.
Save PartyLich/50ad6f87db5f7449c369b1911988eb4f to your computer and use it in GitHub Desktop.
FreeCodeCamp => Algorithms: Pairwise
/**
* @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