day 08 part 2 finished

This commit is contained in:
2024-12-21 11:12:13 +01:00
parent 620f903135
commit c5947508f3
2 changed files with 39 additions and 23 deletions

View File

@ -1,5 +1,10 @@
LLR
LR
AAA = (BBB, BBB)
BBB = (AAA, ZZZ)
ZZZ = (ZZZ, ZZZ)
11A = (11B, XXX)
11B = (XXX, 11Z)
11Z = (11B, XXX)
22A = (22B, XXX)
22B = (22C, 22C)
22C = (22Z, 22Z)
22Z = (22B, 22B)
XXX = (XXX, XXX)

View File

@ -6,50 +6,61 @@ function init(filename) {
data.split('\n\n')[0].split(''),
data.split('\n\n')[1]
)
desertmap.navigate()
desertmap.navigate_ghosts()
}
class DesertMap {
instructions = []
map = ""
#iterator
#route = []
#way = null
constructor(instructions, map) {
this.instructions = instructions
this.map = map
this.#route = []
this.#iterator = 0
this.steps = 0
this.#way = null
}
setup() {
const matches = [...this.map.matchAll(/(\w+) = \((\w+), (\w+)\)/gm)]
matches.forEach(match => {
this.#route.push({ goal: match[1], L: match[2], R: match[3] })
this.#route.push({ from: match[1], L: match[2], R: match[3] })
})
}
run(towards) {
if (!this.steps) {
return this.#route.find(route => route.goal === 'AAA')[towards]
run(towards, from) {
if (!this.steps && !from) {
return this.#route.find(route => route.from === 'AAA')[towards]
}
return this.#route.find(route => route.goal === this.#way)[towards]
return this.#route.find(route => route.from === from)[towards]
}
navigate_ghosts() {
this.setup()
let i = 0
let start = this.#route.filter(route => route.from[2] === 'A')
.map(route => route.from)
while (i < this.instructions.length | true) {
start = start.map(route => this.run(this.instructions[i], route))
++this.steps
if (start.filter(route => route[2] === 'Z').length === start.length) {
console.log(this.steps)
return true
}
i = this.instructions.length - i === 1 ? 0 : i + 1
}
console.log(this.steps + 1)
}
navigate() {
this.setup()
//console.log(this.#route)
while (this.#iterator < this.instructions.length | true) {
this.#way = this.run(this.instructions[this.#iterator])
this.steps += 1
console.log(this.#iterator, this.#way, this.steps)
if (this.#way === 'ZZZ') { return false }
this.#iterator = this.instructions.length - this.#iterator === 1 ? 0 : this.#iterator + 1
let i = 0
while (i < this.instructions.length | true) {
let from = this.run(this.instructions[i], from)
++this.steps
console.log(i, from, this.steps)
if (from === 'ZZZ') { return false }
i = this.instructions.length - i === 1 ? 0 : i + 1
}
console.log(this.steps)
}
}