Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
shahata committed Dec 16, 2023
1 parent 57cc55e commit 987a2ac
Showing 1 changed file with 31 additions and 28 deletions.
59 changes: 31 additions & 28 deletions src/2023/day16.js
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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;
}

0 comments on commit 987a2ac

Please sign in to comment.