freeCodeCamp/Algorithms/pairwise.js
2023-08-22 10:51:35 +10:00

31 lines
876 B
JavaScript

// https://www.freecodecamp.org/learn/coding-interview-prep/algorithms/pairwise
function pairwise(arr, sum) {
const arr2 = arr.map((num, index) => ({ num: num, index: index }));
arr2.sort(({ num: numA, index: indexA }, { num: numB, index: indexB }) => {
if (numA === numB) {
return indexA - indexB;
} else {
return numA - numB;
}
});
let [i, reverseI, pairsIndexSum] = [0, arr2.length - 1, 0];
while (i < reverseI) {
if (arr2[i].num + arr2[reverseI].num === sum) {
if (arr2[i].num === arr2[reverseI].num) {
pairsIndexSum += arr2[i++].index + arr2[i++].index;
} else {
pairsIndexSum += arr2[i++].index + arr2[reverseI--].index;
}
} else if (arr2[i].num + arr2[reverseI].num < sum) {
i++;
} else {
reverseI--;
}
}
return pairsIndexSum;
}
console.log(pairwise([1, 1, 1], 2));