From 987a2acba514a732efabcf0b4b8baa41fece434c Mon Sep 17 00:00:00 2001 From: Shahar Talmi Date: Sat, 16 Dec 2023 09:39:13 +0200 Subject: [PATCH] refactor --- src/2023/day16.js | 59 +++++++++++++++++++++++++---------------------- 1 file changed, 31 insertions(+), 28 deletions(-) diff --git a/src/2023/day16.js b/src/2023/day16.js index d0a2305b..ce555adf 100644 --- a/src/2023/day16.js +++ b/src/2023/day16.js @@ -1,38 +1,42 @@ +function getNextSteps(map, x, y, d) { + const RIGHT = { x: x + 1, y: y, d: 'right' }; + const LEFT = { x: x - 1, y: y, d: 'left' }; + const UP = { x: x, y: y - 1, d: 'up' }; + const DOWN = { x: x, y: y + 1, d: 'down' }; + + if (map[y][x].c === '-' && (d === 'up' || d === 'down')) { + return [LEFT, RIGHT]; + } else if (map[y][x].c === '|' && (d === 'right' || d === 'left')) { + return [UP, DOWN]; + } else if (map[y][x].c === '\\') { + if (d === 'right') return [DOWN]; + if (d === 'left') return [UP]; + if (d === 'up') return [LEFT]; + if (d === 'down') return [RIGHT]; + } else if (map[y][x].c === '/') { + if (d === 'right') return [UP]; + if (d === 'left') return [DOWN]; + if (d === 'up') return [RIGHT]; + if (d === 'down') return [LEFT]; + } else { + if (d === 'right') return [RIGHT]; + if (d === 'left') return [LEFT]; + if (d === 'up') return [UP]; + if (d === 'down') return [DOWN]; + } +} + export function part1(input, start = { x: 0, y: 0, d: 'right' }) { const map = input .split('\n') .map(line => line.split('').map(c => ({ c, l: [] }))); const queue = [start]; while (queue.length > 0) { - let next = []; const { x, y, d } = queue.shift(); - const RIGHT = { x: x + 1, y: y, d: 'right' }; - const LEFT = { x: x - 1, y: y, d: 'left' }; - const UP = { x: x, y: y - 1, d: 'up' }; - const DOWN = { x: x, y: y + 1, d: 'down' }; - + const next = getNextSteps(map, x, y, d).filter( + ({ x, y, d }) => map[y]?.[x]?.l.includes(d) === false, + ); map[y][x].l.push(d); - if (map[y][x].c === '-' && (d === 'up' || d === 'down')) { - next.push(LEFT, RIGHT); - } else if (map[y][x].c === '|' && (d === 'right' || d === 'left')) { - next.push(UP, DOWN); - } else if (map[y][x].c === '\\') { - if (d === 'right') next.push(DOWN); - if (d === 'left') next.push(UP); - if (d === 'up') next.push(LEFT); - if (d === 'down') next.push(RIGHT); - } else if (map[y][x].c === '/') { - if (d === 'right') next.push(UP); - if (d === 'left') next.push(DOWN); - if (d === 'up') next.push(RIGHT); - if (d === 'down') next.push(LEFT); - } else { - if (d === 'right') next.push(RIGHT); - if (d === 'left') next.push(LEFT); - if (d === 'up') next.push(UP); - if (d === 'down') next.push(DOWN); - } - next = next.filter(({ x, y, d }) => map[y]?.[x]?.l.includes(d) === false); queue.push(...next); } return map.flatMap(lines => lines.filter(c => c.l.length > 0)).length; @@ -53,6 +57,5 @@ export function part2(input) { for (let y = 0; y < map.length; y++) { max = Math.max(max, part1(input, { x: map[0].length - 1, y, d: 'left' })); } - return max; }