Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// 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