Created
January 5, 2022 00:28
-
-
Save velsa/4befdf7392a402b5f6064554c732b83a to your computer and use it in GitHub Desktop.
Finds pairs of number in array which produce given sum.
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
// Finds pairs of number in array which produce given sum. | |
const ARRAY_SIZE = 1000; | |
const MAX_NUMBER = 2022; | |
const SUM_TO_FIND = 2022; | |
const arr = new Array(ARRAY_SIZE) | |
.fill(0) | |
.map(() => Math.floor(Math.random() * MAX_NUMBER)); | |
// Sort array, so later we can sum small nums with large nums | |
const sortedArr = arr.sort((a, b) => a - b); | |
// Squash equal numbers into objects with count | |
const squashedArr = []; | |
for (let i = 0; i < sortedArr.length; i++) { | |
if (i > 0 && squashedArr[squashedArr.length - 1].value === sortedArr[i]) { | |
squashedArr[squashedArr.length - 1].count++; | |
} else { | |
squashedArr.push({ value: sortedArr[i], count: 1 }); | |
} | |
} | |
// Now we can do it in one run: | |
// | |
// If last num + first num < SUM_TO_FIND, we drop the first num | |
// If last num + first num > SUM_TO_FIND, we drop the last num | |
// If we found our sum, we drop the count on both nums and remove both nums | |
// | |
while (squashedArr.length > 1) { | |
const last = squashedArr.length - 1; | |
const sum = squashedArr[0].value + squashedArr[last].value; | |
if (sum > SUM_TO_FIND) { | |
squashedArr.pop(); | |
continue; | |
} | |
if (sum < SUM_TO_FIND) { | |
squashedArr.shift(); | |
continue; | |
} | |
const dec = Math.min(squashedArr[0].count, squashedArr[last].count); | |
squashedArr[0].count -= dec; | |
squashedArr[last].count -= dec; | |
console.log( | |
`Found ${dec} pair${dec > 1 ? "s" : ""}:`, | |
squashedArr[0].value, | |
squashedArr[last].value | |
); | |
squashedArr.shift(); | |
squashedArr.pop(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment