Skip to content

Instantly share code, notes, and snippets.

@warriordog
Created December 14, 2020 18:07
Show Gist options
  • Save warriordog/d6a646eece0a4ec7cd941e8c0efcd9a7 to your computer and use it in GitHub Desktop.
Save warriordog/d6a646eece0a4ec7cd941e8c0efcd9a7 to your computer and use it in GitHub Desktop.
Solution to Advent of Code 2020 Day 14 Part 1
const { parseInputFile } = require('../utils/parser');
const inputs = parseInputFile('day14-input.txt', /^(mask|mem)(?:\[(\d+)\])? = ([0-9X]+)$/gm)
.map(([, ins, addr, maskOrValue]) => {
switch (ins) {
case 'mask': return {
ins,
mask: maskOrValue,
maskOR: BigInt(parseInt(maskOrValue.replace(/X/g, '0'), 2)),
maskAND: BigInt(parseInt(maskOrValue.replace(/X/g, '1'), 2))
};
case 'mem': return {
ins,
addr: BigInt(parseInt(addr)),
value: BigInt(parseInt(maskOrValue))
};
default: throw new Error(`Invalid instruction: ${ ins }`);
}
});
/** @type {Map<bigint, bigint>} */
const mem = new Map();
let maskAND = 0n;
let maskOR = 0n;
for (const instruction of inputs) {
if (instruction.ins === 'mask') {
maskAND = instruction.maskAND;
maskOR = instruction.maskOR;
} else { // can only be "mem" here
const value = (instruction.value & maskAND) | maskOR;
mem.set(instruction.addr, value);
}
}
const part1Answer = Array.from(mem.values()).reduce((total, v) => total + v, 0n);
console.log(`Part 1: ${ part1Answer }`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment