Published
Edited
Dec 10, 2021
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
getIncreaseCount = input => {
const measurements = input.trim().split('\n').map(d => +d)
// If an entry is greater than the previous entry, add 1 to the accumulator
return measurements.reduce((acc, m, i, arr) => m > arr[i - 1] ? acc + 1 : acc, 0)
}
Insert cell
Insert cell
getIncreaseCount(dayOneExampleInput)
Insert cell
Insert cell
getIncreaseCount(await FileAttachment("input1.txt").text())
Insert cell
Insert cell
getIncreaseCountWithWindow = (input, windowSize = 3) => {
const measurements = input.trim().split('\n').map(d => +d)
// Create an array of 3-element windows
const windows = d3.range(windowSize, measurements.length + 1).map(i => measurements.slice(i - windowSize, i))
// If a previous window exists and the current window is larger, add 1 to the accumulator
return windows.reduce((acc, m, i, arr) => (i > 0) && (d3.sum(m) > d3.sum(arr[i - 1])) ? acc + 1 : acc, 0)
}
Insert cell
Insert cell
getIncreaseCountWithWindow(dayOneExampleInput)
Insert cell
Insert cell
getIncreaseCountWithWindow(await FileAttachment("input1.txt").text())
Insert cell
Insert cell
Insert cell
Insert cell
parseSubmarineCommands = input => input.trim().split('\n').map(d => d.split(' ')).map(([cmd, n]) => [cmd, +n])
Insert cell
executeSubmarineCommands = input => parseSubmarineCommands(input)
.reduce(([curX, curY], [dir, amt]) => {
if (dir === 'forward') return [curX + amt, curY]
if (dir === 'down') return [curX, curY + amt]
if (dir === 'up') return [curX, curY - amt]
}, [0, 0])
Insert cell
Insert cell
executeSubmarineCommands(dayTwoExampleInput)
Insert cell
Insert cell
dayTwoPartOneAnswer = executeSubmarineCommands(await FileAttachment("input2.txt").text())
Insert cell
Insert cell
dayTwoPartOneAnswer[0] * dayTwoPartOneAnswer[1]
Insert cell
Insert cell
executeSubmarineCommands2 = input => parseSubmarineCommands(input)
.reduce(([curX, curY, aim], [dir, amt]) => {
if (dir === 'forward') return [curX + amt, curY + aim * amt, aim]
if (dir === 'down') return [curX, curY, aim + amt]
if (dir === 'up') return [curX, curY, aim - amt]
}, [0, 0, 0])
Insert cell
Insert cell
executeSubmarineCommands2(dayTwoExampleInput)
Insert cell
Insert cell
dayTwoPartTwoAnswer = executeSubmarineCommands2(await FileAttachment("input2.txt").text())
Insert cell
Insert cell
dayTwoPartTwoAnswer[0] * dayTwoPartTwoAnswer[1]
Insert cell
Insert cell
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