Public
Edited
Dec 1, 2023
Insert cell
Insert cell
Insert cell
Insert cell
function parse(input) {
const circuit = new Map();
for (const instr of input.split("\n")) {
const [input, output] = instr.trim().split(/\s+->\s+/);
circuit.set(output, input.split(/\s+/));
}
return circuit;
}
Insert cell
Insert cell
operators = ({
AND: (a, b) => a & b,
OR: (a, b) => a | b,
LSHIFT: (a, b) => (a << b) & 65535,
RSHIFT: (a, b) => a >> b
})
Insert cell
Insert cell
function build(circuit, memo = new Map()) {
const evaluate = (wire) => {
if (!isNaN(Number(wire))) {
// Do we have a numeric literal?
return Number(wire);
}
if (memo.has(wire)) {
// Check memo table for previously evaluated results.
return memo.get(wire);
}

// Recursively evaluate the expression
const expr = circuit.get(wire);
const value =
expr.length === 1
? evaluate(expr[0])
: expr[0] === "NOT"
? ~evaluate(expr[1])
: operators[expr[1]](evaluate(expr[0]), evaluate(expr[2]));
memo.set(wire, value); // Update the memo table with the evaluated result.
return value;
};

return evaluate("a");
}
Insert cell
function part1(input) {
return build(parse(input));
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function part2(input) {
return build(parse(input), new Map([["b", part1(input)]]));
}
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