Day 24 Part 1
This commit is contained in:
54
2024/24/index.ts
Normal file
54
2024/24/index.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
const fs = require('fs');
|
||||
|
||||
const input = fs.readFileSync(__dirname + '/input.txt', 'utf8');
|
||||
|
||||
const [initStr, gatesStr] = input.split("\n\n");
|
||||
|
||||
const valMap: { [key: string]: number }= {};
|
||||
const gateMap: { [key: string]: [string, string, string] } = {};
|
||||
|
||||
const outputWires: Array<string> = [];
|
||||
|
||||
initStr.split("\n").forEach((s: string) => {
|
||||
const [wire, val] = s.split(': ');
|
||||
valMap[wire] = parseInt(val, 2);
|
||||
});
|
||||
|
||||
gatesStr.split("\n").forEach((s: string) => {
|
||||
const [inp, out] = s.split(' -> ');
|
||||
const [val1, op, val2] = inp.split(' ');
|
||||
gateMap[out] = [val1, op, val2];
|
||||
if (out.startsWith('z')) {
|
||||
outputWires.push(out);
|
||||
}
|
||||
});
|
||||
|
||||
function getWireVal(wire: string): number {
|
||||
if (Object.hasOwn(valMap, wire)) {
|
||||
return valMap[wire];
|
||||
}
|
||||
const val = getVal(...gateMap[wire])
|
||||
valMap[wire] = val;
|
||||
return val;
|
||||
}
|
||||
|
||||
function getVal(wire1: string, op: string, wire2: string): number {
|
||||
const val1 = getWireVal(wire1);
|
||||
const val2 = getWireVal(wire2);
|
||||
|
||||
return {
|
||||
AND: () => val1 & val2,
|
||||
OR: () => val1 | val2,
|
||||
XOR: () => val1 ^ val2,
|
||||
}[op]!();
|
||||
}
|
||||
|
||||
outputWires.sort().reverse();
|
||||
|
||||
let outputStr = '';
|
||||
|
||||
outputWires.forEach((wire) => {
|
||||
outputStr += getWireVal(wire);
|
||||
});
|
||||
|
||||
console.log(outputStr, parseInt(outputStr, 2));
|
||||
Reference in New Issue
Block a user