advent of code 2023 day 16: fixed recursion error, still something wrong when turning, no idea what

This commit is contained in:
Wouter Groeneveld 2023-12-16 19:34:51 +01:00
parent 954e19cf6b
commit 56bd065fe6
1 changed files with 16 additions and 4 deletions

View File

@ -23,27 +23,39 @@ const mirrors = {
const solve = (input) => {
const tiles = input.split('\n').map(line => line.split(''))
const energized = []
const outOfBounds = (pos) => pos[0] < 0 || pos[1] < 0 || pos[0] >= tiles.length || pos[1] >= tiles[0].length
const alreadyVisitedWithSameDirection = (pos, direction) => energized.find(e => e[0] === pos[0] && e[1] === pos[1] && e[2] === direction)
const traverse = (pos, direction) => {
if(pos[0] < 0 || pos[1] < 0 || pos[0] > tiles.length || pos[1] > tiles[0].length)
if(outOfBounds(pos) || alreadyVisitedWithSameDirection(pos, direction))
return
const curr = tiles[pos[0]][pos[1]]
energized.push(pos)
console.log(`trav ${pos} curr ${curr} direction ${direction}`)
energized.push([pos[0], pos[1], direction])
if(curr === '/' || curr === '\\') {
direction = mirrors[curr][direction]
} else if(curr === '|' && (direction === "L" || direction === "R")) {
traverse([pos[0] + directions["U"][0], pos[1] + directions["U"][1]], "U")
traverse([pos[0] + directions["D"][0], pos[1] + directions["D"][1]], "D")
} else if(curr === '-' && (direction === "U" || direction === "D")) {
// I think the stop condition for the recursion is wonky? Doing R first creates a stack overflow.
traverse([pos[0] + directions["L"][0], pos[1] + directions["L"][1]], "L")
traverse([pos[0] + directions["R"][0], pos[1] + directions["R"][1]], "R")
}
traverse([pos[0] + directions[direction][0], pos[1] + directions[direction][1]], direction)
}
traverse([0, 0], "R")
return new Set(energized).size
const print = () => {
toprint = []
tiles.forEach(t => toprint.push('.'.repeat(t.length).split('')))
energized.forEach(e => toprint[e[0]][e[1]] = '#')
console.log(toprint.map(tp => tp.join('')).join('\n'))
}
print()
// JS can't do obj/arr-in-arr Set comparisons, so I cheat by converting [1, 2] to "1,2"
return new Set(energized.map(e => [e[0], e[1]].toString())).size
}
module.exports = {