Public
Edited
Dec 20, 2022
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
samplingPoints = R.range(0, 6).map(x => x * 40 + 20)
Insert cell
describe('solvePart1', () => {
it('solves for exampleInput2', () => {
expect(solvePart1(exampleInput2)).toBe(13140)
})
})
Insert cell
solvePart1 = R.pipe(
simulateProgram,
history => R.map(samplingPoint => getSignalStrength(samplingPoint, history), samplingPoints),
R.sum
)
Insert cell
solvePart1(input)
Insert cell
Insert cell
simulationResult = simulateProgram(input)
Insert cell
getPixel = R.curry((history, samplingPoint) => {
const x = Math.floor(samplingPoint % 40)
const {X} = getSimulationStateDuringCycle(samplingPoint, history)
return Math.abs(x - X - 1) <= 1 ? (renderMoreReadable ? '█' : '#') : (renderMoreReadable ? ' ' : '.')
})
Insert cell
Insert cell
image2 = R.pipe(
R.map(getPixel(simulationResult)),
R.splitEvery(40),
R.map(R.join('')),
R.join('\n'),
s => htl.html`<pre>${s}</pre>`
)(R.range(1, 241))
Insert cell
Insert cell
parseInstructions(exampleInput)
Insert cell
parseInstructions = R.pipe(
R.split('\n'),
R.map(parseInstruction)
)
Insert cell
parseInstruction = R.pipe(
token => /^(?<instruction>\w+)\s?(?<argument>.+)?$/.exec(token),
R.tap(token => console.log(token)),
x => x.groups,
({instruction, argument}) => instruction.startsWith('add')
? {type: 'add', register: instruction.replace('add', '').toUpperCase(), value: parseInt(argument)}
: {type: instruction}
)
Insert cell
Insert cell
simulateProgram = R.pipe(
parseInstructions,
simulate(executeInstruction, initialize())
)
Insert cell
Insert cell
getSimulationStateDuringCycle = R.curry((cycles, history) => R.findLast(x => x.cycles < cycles, history))
Insert cell
Insert cell
getSignalStrength = (samplingPoint, history) => {
const {X, cycles} = getSimulationStateDuringCycle(samplingPoint, history)

return X * samplingPoint
}
Insert cell
runProgram = R.pipe(
simulateProgram,
R.last
)
Insert cell
initialize = () => ({X: 1, cycles: 0})
Insert cell
Insert cell
executeInstruction = (instruction, state) => {
const newState = {...state}
if (instruction.type === 'noop') {
newState.cycles += 1
}
if (instruction.type === 'add') {
newState[instruction.register] += instruction.value
newState.cycles += 2
}
return newState
}
Insert cell
Insert cell
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