Last active
December 1, 2020 08:13
-
-
Save jazzyjackson/a198852ab2010db35c0bb24d53e9eb8e to your computer and use it in GitHub Desktop.
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
// blackjack sum | |
// given a goal sum and a list of integers, find pairs that add up to the goal | |
// return their product | |
// worse-case quadratic, for each in the list, I check all possibilities from the bottom up | |
// start at the highest number, scan up from the bottom, as soon as I break my goal I exit | |
let goal = 2020 | |
let bottomup = [1721, 979, 366, 299, 675, 1456].sort((a,b) => a - b) // sort from the largest to the smallest | |
let topdown = bottomup.slice().reverse() | |
outer: | |
for(var j = topdown.length; j > 0; --j){ | |
inner: | |
for(var k = 0; k < bottomup.length; k++){ | |
if(topdown[j] + bottomup[k] > goal){ | |
// if we overshoot, break out of the inner increment and move onto the next value from "topdown" | |
break inner | |
} | |
if(topdown[j] + bottomup[k] === goal){ | |
// if we get a match, break out of the whole program | |
console.log(`${topdown[j]} * ${bottomup[k]} = ${topdown[j] * bottomup[k]}`) | |
// 299 * 1721 = 514579 | |
break outer | |
} | |
// otherwise, no sum found, move onto the next one down | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment