Created
January 6, 2020 15:16
-
-
Save und3f/6d183a4cf51828e7790b50c01f31df57 to your computer and use it in GitHub Desktop.
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
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