Published
Edited
Dec 14, 2020
1 fork
1 star
Insert cell
Insert cell
lines = input.trim().split('\n')
Insert cell
function parseMask(pattern) {
const or = pattern.replace(/[^1]/g, '0')
const and = pattern.replace(/[^0]/g, '1')
return {or: BigInt(parseInt(or, 2)), and: BigInt(parseInt(and, 2))}
}
Insert cell
function apply(mask, value) {
return (value | mask.or) & mask.and
}
Insert cell
part1 = {
let mask = null
const mem = {}
for (const line of lines) {
if (line.match(/^mask = /)) {
mask = parseMask(line.split(' = ')[1])
} else {
const [, i, value] = line.match(/^mem\[(\d+)\] = (\d+)$/)
mem[+i] = apply(mask, BigInt(value))
}
}
// return mem
return Object.values(mem).reduce((sum, d) => sum + d)
}
Insert cell
function parseFloatingMask(pattern) {
const or = pattern.replace(/[^10]/g, '0')
const floating = pattern.split('').reverse().map((b, i) => b === 'X' ? i : null).filter(i => i !== null)
return {or: BigInt(parseInt(or, 2)), floating: floating}
}
Insert cell
parseFloatingMask(lines[0])
Insert cell
[...applyFloatingMask(parseFloatingMask(lines[0].split(' = ')[1]), 42n)]
Insert cell
function* applyFloatingMask(mask, address) {
const r = address | mask.or
for (let i = 0; i < (1<<mask.floating.length); i++) {
// build floating mask
const f = new Array(36).fill('X')
for (let j = 0; j < mask.floating.length; j++) {
const b = mask.floating[j]
f[b] = (i >> j) & 1
}
const floatingMask = parseMask(f.reverse().join(''))
yield apply(floatingMask, r)
}
}
Insert cell
part2 = {
let mask = null
const mem = {}
for (const line of lines) {
if (line.match(/^mask = /)) {
mask = parseFloatingMask(line.split(' = ')[1])
} else {
const [, i, value] = line.match(/^mem\[(\d+)\] = (\d+)$/)
for (const i2 of applyFloatingMask(mask, BigInt(i)))
mem[i2] = +value
}
}
// return mem
return Object.values(mem).reduce((sum, d) => sum + d)
}
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