import fs from 'node:fs' function init(filename) { const data = fs.readFileSync(filename, { encoding: 'utf-8' }, data => data) const desertmap = new DesertMap( data.split('\n\n')[0].split(''), data.split('\n\n')[1] ) desertmap.navigate() } 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] }) }) } run(towards) { if (!this.steps) { return this.#route.find(route => route.goal === 'AAA')[towards] } return this.#route.find(route => route.goal === this.#way)[towards] } 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 } console.log(this.steps) } } init('input.txt')