Public
Edited
Sep 17, 2023
1 star
Insert cell
Insert cell
Insert cell
function parse(input) {
const parseLine = (s) => {
const toBits = (n) => AOC.decToBinary(n, 36).split("");
const matches = s
.match(/mask = ([01X]+)|mem\[(\d+)\] = (\d+)/)
.slice(1)
.filter(AOC.identity);

return matches.length == 2
? {
addr: AOC.decToBinary(matches[0], 36),
val: AOC.decToBinary(matches[1], 36).split("")
}
: { mask: matches[0].split("") };
};
return input.split("\n").map(parseLine);
}
Insert cell
Insert cell
function applyMask(mask, val) {
const combine = (b1, b2) => (b1 === "0" ? 0 : b1 === "1" ? 1 : b2);
return parseInt(AOC.zipWith(combine, mask, val).join(""), 2);
}
Insert cell
Insert cell
function run(state, cmd) {
if ("mask" in cmd) {
state.mask = cmd.mask;
} else {
state.mem[cmd.addr] = applyMask(state.mask, cmd.val);
}
return state;
}
Insert cell
function part1(input) {
return AOC.sum(Object.values(parse(input).reduce(run, { mem: {} }).mem));
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function xPositions(mask) {
const positions = [];
mask.forEach((chr, i) => {
if (chr === "X") positions.push(i);
});
return positions;
}
Insert cell
function applyMask2(mask, val) {
const combine = (b1, b2) => (b1 === "0" ? b2 : b1);
const addr = AOC.zipWith(combine, mask, val);
const xps = xPositions(mask, val);
const addrs = [...Array(Math.pow(2, xps.length)).keys()].map((n) =>
AOC.decToBinary(n, xps.length).split("")
);

return addrs.map((digits) => {
const newAddr = AOC.cloneArray(addr);
digits.forEach((d, i) => (newAddr[xps[i]] = d));
return newAddr.join("");
});
}
Insert cell
Insert cell
function run2(state, cmd) {
if ("mask" in cmd) {
state.mask = cmd.mask;
} else {
applyMask2(state.mask, cmd.addr).forEach(
(addr) => (state.mem[addr] = parseInt(cmd.val.join(""), 2))
);
}
return state;
}
Insert cell
function part2(input) {
return AOC.sum(Object.values(parse(input).reduce(run2, { mem: {} }).mem));
}
Insert cell
Insert cell
Insert cell
Insert cell
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