78 lines
2.3 KiB
JavaScript
78 lines
2.3 KiB
JavaScript
import fs from 'node:fs'
|
|
|
|
function init(filename) {
|
|
const data = fs.readFileSync(filename, { encoding: 'utf-8' }, data => data)
|
|
const device = new Device()
|
|
const Wires = data.split('\n\n')[0].split('\n')
|
|
const Gates = data.split('\n\n')[1].split('\n')
|
|
Wires.forEach((wire, index) => {
|
|
let [name, value] = wire.split(':')
|
|
device.Wires.push({
|
|
name: name,
|
|
value: parseInt(value.trim())
|
|
})
|
|
})
|
|
|
|
Gates.forEach((gate, index) => {
|
|
let [w1, operator, w2, _null, output] = gate.split(' ')
|
|
device.Gates.push({
|
|
wire1: w1,
|
|
operator: operator,
|
|
wire2: w2,
|
|
output: output
|
|
})
|
|
})
|
|
device.part1()
|
|
}
|
|
|
|
class Device {
|
|
constructor() {
|
|
this.Wires = []
|
|
this.Gates = []
|
|
}
|
|
|
|
getWire(wire) {
|
|
return this.Wires.find(Wire => wire === Wire.name).value
|
|
}
|
|
|
|
generateOutput(w1, w2, operator) {
|
|
let result = 0
|
|
switch (operator) {
|
|
case 'AND':
|
|
result = this.getWire(w1) && this.getWire(w2)
|
|
break;
|
|
case 'OR':
|
|
result = this.getWire(w1) || this.getWire(w2)
|
|
break;
|
|
case 'XOR':
|
|
result = this.getWire(w1) ^ this.getWire(w2)
|
|
break;
|
|
default: break
|
|
}
|
|
return result
|
|
}
|
|
part1() {
|
|
let i = 0
|
|
while (this.Gates.length > 0) {
|
|
if (this.Wires.some(wire => wire.name === this.Gates[i].wire1) &&
|
|
this.Wires.some(wire => wire.name === this.Gates[i].wire2)
|
|
) {
|
|
let result = this.generateOutput(this.Gates[i].wire1, this.Gates[i].wire2, this.Gates[i].operator)
|
|
this.Wires.push({ name: this.Gates[i].output, value: result })
|
|
}
|
|
else { // this configuration cannot yet be determined, pushing back to the end of array
|
|
this.Gates.push(this.Gates[i])
|
|
}
|
|
this.Gates.splice(i, 1)
|
|
}
|
|
|
|
let result = this.Wires.filter(wire => String(wire.name).startsWith('z')).sort((a, b) => a.name < b.name ? -1 : 1).reduce((prev, current, index) => {
|
|
return (current.value === 1) ? prev + Math.pow(2, index) : prev;
|
|
}, 0);
|
|
|
|
console.log(result)
|
|
}
|
|
|
|
}
|
|
|
|
init('input.txt') |