Skip to content

Instantly share code, notes, and snippets.

@mauroc8
Last active December 2, 2020 02:50
Show Gist options
  • Save mauroc8/66db1210306cebdd5519d5d2ba9a940c to your computer and use it in GitHub Desktop.
Save mauroc8/66db1210306cebdd5519d5d2ba9a940c to your computer and use it in GitHub Desktop.
const numbers =
input
.trim()
.split("\n")
.map(Number)
const sums =
numbers
.flatMap(n =>
numbers.map(k => n + k))
const floor =
Math.floor
const length =
numbers.length
const productAtIndex =
i =>
numbers[floor(i / length)]
* numbers[i % length]
const answer =
sums
.reduce((answer, sum, i) =>
Math.max(answer, sum == 2020 ? productAtIndex(i) : 0),
0
)
answer
// Part 2 ---
const numbers =
input
.trim()
.split("\n")
.map(Number)
const sums =
numbers
.flatMap(n => numbers.map(k => r => n + k + r))
.flatMap(f => numbers.map(f))
const floor =
Math.floor
const length =
numbers.length
const productAtIndex =
i =>
numbers[i % length]
* numbers[floor(i / length) % length]
* numbers[floor(i / length / length) % length]
const answer =
sums
.reduce((answer, sum, i) =>
Math.max(answer, sum == 2020 ? productAtIndex(i) : 0),
0
)
answer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment