Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// Find the complement to each highest number and search the lower numbers for the complement
// So it could be recursive, given a sorted array, loop through it from the top down, handing the lower half of the list to yourself
// base case: I have 2 numbers to fill.
let goal = 2020
let list = [1721, 979, 366, 299, 675, 1456]
let [a,b] = findsum(list, goal, 2)
console.log(a, b, a + b, a * b)
// 1721 299 2020 514579
let [x,y,z] = findsum(list, goal, 3)
console.log(x,y,z,x+y+z, x*y*z)
// 979 366 675 2020 241861950
function findsum(all, target, n){
if(n > 2){
for(var each of all){
let complement = target - each
let result = findsum(all.slice(0,-1), complement, n - 1)
if(result){
return [].concat(each, result)
} // otherwise try the next one
} // if we run out of things to try return undefined
} else { // I do have two
let marbles = new Set(all)
for(var marble of marbles){
let complement = target - marble
if(marbles.has(complement)){
return [marble, complement]
} // else try the next marble
} // if I don't find any solutions I return undefined and the function caller knows I couldn't find anything
}
}
// basically I'm finding the complementary list -- hand down a list of how many numbers I need, and what they need to equal
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment