const fs = require("fs"); const input = fs.readFileSync("input", "utf-8").trim().split("\n"); function main() { // original mask string let mask = null; const memory = []; for (const line of input) { if (line.startsWith("mask")) { mask = line.slice(7); } else { const address = parseInt(line.slice(4)); const num = BigInt(parseInt(line.split(" = ")[1])); memory[address] = apply(num, mask); // debug(num, mask); } } const sum = memory.reduce((a, b) => a + b, 0n); console.log("Solution:"); console.log(sum.toString()); } function debug(value, mask) { const result = apply(value, mask); console.log("=".repeat(18), " DEBUG ", "=".repeat(18)); console.log(`value: ${numToBin(value)} (decimal ${value})`); console.log(`mask: ${mask}`); console.log(`result: ${numToBin(result)} (decimal ${result})`); } function numToBin(num) { return num.toString(2).padStart(36, "0"); } function binToNum(bin) { return BigInt(parseInt(bin, 2)); } function apply(num, mask) { num = num & binToNum(mask.replaceAll("X", 1)); num = num | binToNum(mask.replaceAll("X", 0)); return num; } main();