Skip to content

Instantly share code, notes, and snippets.

@und3f
Created January 6, 2020 15:16
Show Gist options
  • Save und3f/6d183a4cf51828e7790b50c01f31df57 to your computer and use it in GitHub Desktop.
Save und3f/6d183a4cf51828e7790b50c01f31df57 to your computer and use it in GitHub Desktop.
Pairwise
function pairwise(arr, arg) {
let sum = 0;
let arrIndexes = arr.map((v, i) => i);
arrIndexes.sort((a, b) => {
let s = arr[a] - arr[b];
if (s === 0)
s = b - a;
return s;
});
let middle = Math.ceil(arg/2) || 1;
let j = arrIndexes.findIndex((v) => arr[v] >= middle);
if (j === -1)
return 0;
// If there are a bunch of numbers arg/2 set pointer correctly
if (arr[arrIndexes[j]] * 2 === arg) {
let k = j;
for (k = j; k < arrIndexes.length && arr[arrIndexes[k]] === middle; k++) {}
let totalNumbers = k - j;
if (totalNumbers % 2 === 1)
--totalNumbers;
j = k - totalNumbers/2;
}
let i = j-1;
while (i >= 0 && j < arrIndexes.length) {
let currentSum = arr[arrIndexes[i]] + arr[arrIndexes[j]];
if (currentSum === arg) {
sum += arrIndexes[i];
sum += arrIndexes[j];
i--;
j++;
} else if (currentSum > arg) {
i--;
} else
j++;
}
return sum;
}
console.log(pairwise([1, 1, 1, 1, 1, 1, 1, 1], 2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment