Published
Edited
Dec 12, 2020
1 fork
1 star
Insert cell
Insert cell
joltages = input.trim().split('\n').map(Number)
Insert cell
device = Math.max(...joltages) + 3
Insert cell
ordered = [0, ...joltages.sort((a, b) => a - b), device]
Insert cell
differences = ordered.map((j, i) => ordered[i + 1] - j)
Insert cell
distribution = d3.rollup(differences, r => r.length, d => d)
Insert cell
part1 = distribution.get(1) * distribution.get(3)
Insert cell
function beyond(next, last, cache = new Map()) {
const key = String([last, next])
if (cache.has(key)) return cache.get(key)

const possible = next.filter(n => n <= last + 3)
if (possible.length) {
const sum = possible.reduce((sum, p) => {
const withoutP = next.slice(next.findIndex(n => n === p) + 1)
return sum + beyond(withoutP, p, cache)
}, 0)
return cache.set(key, sum), sum
} else {
return cache.set(key, 1), 1
}
}
Insert cell
part2 = beyond(ordered.slice(1), 0)
Insert cell
Insert cell
Insert cell
Insert cell
d3 = require('d3-array@2')
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more