Skip to content

Instantly share code, notes, and snippets.

@vporoshok
Created February 13, 2018 16:20
Show Gist options
  • Select an option

  • Save vporoshok/7353fd7f995f6710ee0db4083a01a7af to your computer and use it in GitHub Desktop.

Select an option

Save vporoshok/7353fd7f995f6710ee0db4083a01a7af to your computer and use it in GitHub Desktop.
export function pairwise (values: number[], check: number): number {
const sorted = Array.from(values.entries());
sorted.sort((a, b) => {
let res = Math.sign(a[1] - b[1]);
if (res === 0) {
res = Math.sign(a[0] - b[0]);
}
return res;
});
let i = 0;
let j = sorted.length - 1;
let total = 0;
while (i < j) {
const sum = sorted[i][1] + sorted[j][1];
if (sum < check) {
i++;
continue;
}
if (sum > check) {
j--;
continue;
}
let k = j - 1;
while (k > i && sorted[k][1] === sorted[j][1]) {
k--;
}
k++;
total += sorted[i][0] + sorted[k][0];
i++;
j = k - 1;
}
return total;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment