Skip to content

Instantly share code, notes, and snippets.

@cranderveldt
Created December 9, 2020 20:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cranderveldt/05514c9829a9439ddbb3acea5084af47 to your computer and use it in GitHub Desktop.
Save cranderveldt/05514c9829a9439ddbb3acea5084af47 to your computer and use it in GitHub Desktop.
Advent of Code 2020 Day 9
const puzzleInput = ``
// Part 1
const parseInput = (input) => {
return input.split(/\n/).map(x => parseInt(x))
}
const findInvalidNumber = (numbers) => {
return numbers.reduce((acc, number, index) => {
if (index < 25) { return acc }
let found = null
for (let i = -1; i>=-25; i--) {
const target = number - numbers[index + i]
found = numbers.slice(index - 25, index).find(x => x === target)
if (found) { break }
}
return found ? acc : number
}, 0)
}
const partOne = (input) => {
const numbers = parseInput(input)
const result = findInvalidNumber(numbers)
console.log(result)
}
partOne(puzzleInput)
// Part 2
const findContiguousSum = (numbers, sum) => {
for (let index = 0; index < numbers.length; index++) {
let total = 0
for (let subIndex = index; total < sum; subIndex++) {
total += numbers[subIndex]
if (total === sum) {
const subset = numbers.slice(index, subIndex + 1).sort()
return subset[0] + subset[subset.length - 1]
}
}
}
}
const partTwo = (input) => {
const numbers = parseInput(input)
const invalid = findInvalidNumber(numbers)
const weakness = findContiguousSum(numbers, invalid)
console.log(weakness)
}
partTwo(puzzleInput)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment