Skip to content

Latest commit

 

History

History
66 lines (50 loc) · 8.46 KB

09.md

File metadata and controls

66 lines (50 loc) · 8.46 KB

Day 09

Part 1

Starting from the 26th number, find the first number that is not the sum of any two of the previous 25 numbers.

const numbers = input.split('\n').map((str) => +str)

const segmentSize = 25
const part1 = numbers.find((n, i) => {
  if (i < segmentSize) return false
  const segment = numbers.slice(i - segmentSize, i)
  return !segment.find((x, j) => segment.slice(j + 1).find((y) => x + y === n))
})
console.log('Part 1:', part1)

Flems link in Part 2.

This was quite similar to the 2020/01 puzzle.

Part 2

Find a contiguous set of at least two numbers in your list which sum to the invalid number from Part 1. Add together the smallest and largest number in this contiguous range.

const part2 = (() => {
  let range

  numbers.find((x, i) => {
    let acc = x
    range = [x]
    numbers.slice(i + 1).find((y) => {
      acc += y
      range.push(y)
      return acc >= part1
    })
    return acc === part1
  })

  return Math.min(...range) + Math.max(...range)
})()
console.log('Part 2:', part2)

Try out the final code on flems.io

Using find()s like this feels a bit hacky as I'm not even using their return values. But they stop the loops early when a result has been found, so in that regard they are better than e.g. filter() or reduce().

Because there are mutable variables, I wrapper Part 2's code in an IIFE.

What did I learn?

Nothing; this puzzle was a quick one.