Files
2025-12-07 12:46:15 +01:00

94 lines
2.4 KiB
TypeScript

import fs from 'node:fs';
const file = fs.readFileSync('./2025/inputs/7').toString();
const lines = file.split("\n").map(e => e.split(""))
const table: Node[][] = []
const nodes: Node[] = []
let origin: Node | null = null
class Node {
isBeam = false
isSplitter = false
left: Node | null = null
right: Node | null = null
weight = 0
constructor(public x: number, public y: number, public character: string) {
if (this.character == "^") {
this.isSplitter = true
nodes.push(this)
}
if (this.character == "S") {
this.isBeam = true
origin = this
}
}
buildGraph() {
let searchY = this.y + 1
while (searchY < table.length && (!this.left || !this.right)) {
if (this.x > 0 && !this.left && table[searchY][this.x - 1].isSplitter) {
this.left = table[searchY][this.x - 1]
}
if (this.x + 1 < table[searchY].length && !this.right && table[searchY][this.x + 1].isSplitter) {
this.right = table[searchY][this.x + 1]
}
searchY++
}
}
calculateWeight() {
if (this.weight) {
return this.weight
}
let leftC = 1
if (this.left) {
leftC = this.left.calculateWeight()
}
let rightC = 1
if (this.right) {
rightC = this.right.calculateWeight()
}
this.weight = leftC + rightC
return this.weight
}
toString() {
if (this.isSplitter) { return "^" }
if (this.isBeam) { return "|" }
return "."
}
}
table.push(...lines.map((l, i) => l.map((e, j) => new Node(j, i, e))))
table.forEach((line, lineN) => {
if (lineN == 0) {
return
}
line.forEach((node, colN) => {
if (!table[lineN - 1][colN].isBeam) { return }
if (!node.isSplitter) {
node.isBeam = true
return
}
if (colN != 0) {
if (!table[lineN][colN - 1].isBeam) {
table[lineN][colN - 1].isBeam = true
}
}
if (colN + 1 < line.length) {
if (!table[lineN][colN + 1].isBeam) {
table[lineN][colN + 1].isBeam = true
}
}
})
})
nodes.forEach(n => n.buildGraph());
origin = origin as unknown as Node
origin.buildGraph()
console.log(origin.calculateWeight())