Files
advent-of-code/2024/24/index.js

72 lines
1.9 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 = []
this.Outputs = []
}
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() {
this.Gates.forEach(gate => {
let result = this.generateOutput(gate.wire1, gate.wire2, gate.operator)
this.Outputs.push({ name: gate.output, value: result })
})
let result = 0
this.Outputs.sort((a, b) => a.name - b.name).forEach((output, index) => {
result += output.value * (index ** 2)
})
console.log(this.Outputs)
console.log(result)
}
}
init('example.txt')