Last active
December 10, 2020 21:01
-
-
Save cranderveldt/ac037c63aa0a069a399e4b5f9aca8284 to your computer and use it in GitHub Desktop.
Advent of Code 2020 Day 10
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const puzzleInput = `` | |
// Part 1 | |
const parseInput = (input) => { | |
return input.split(/\n/).map(x => parseInt(x)) | |
} | |
const getDifferences = (adapters) => { | |
return adapters.map((adapter, index) => { | |
let prev = adapters[index - 1] || 0 | |
return adapter - prev | |
}) | |
} | |
const countDifferences = (differences) => { | |
return differences.reduce((acc, diff) => { | |
++acc[diff] | |
return acc | |
}, { 1: 0, 3: 1 }) | |
} | |
const partOne = (input) => { | |
const adapters = parseInput(input).sort((a, b) => a - b) | |
const differences = getDifferences(adapters) | |
const values = countDifferences(differences) | |
console.log(values[1] * values[3]) | |
} | |
partOne(puzzleInput) | |
// Part 2 | |
const prevThree = (adapters, index) => { | |
return [1, 2, 3].map(x => adapters[index - x] || 0) | |
} | |
const partTwo = (input) => { | |
const adapters = parseInput(input).sort((a, b) => b - a) | |
adapters.unshift(adapters[0] + 3) | |
adapters.push(0) | |
const configurations = [1] | |
for (let index = 1; index < adapters.length; index++) { | |
const adapter = adapters[index] | |
const config = prevThree(adapters, index).reduce((acc, prev, offset) => { | |
const prevIndex = index - offset - 1 | |
return acc + ((prev - adapter < 4) ? (configurations[prevIndex] || 0) : 0) | |
}, 0) | |
configurations.push(config) | |
} | |
console.log(configurations[configurations.length - 1]) | |
} | |
partTwo(puzzleInput) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment