Skip to content

Commit 536ea2a

Browse files
committed
2024 day 6 cleanup
1 parent a6d1405 commit 536ea2a

File tree

1 file changed

+7
-8
lines changed

1 file changed

+7
-8
lines changed

2024/js/day6.js

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@ const dirs = { '^': [0, -1, '>'], 'v': [0, 1, '<'], '<': [-1, 0, '^'], '>': [1,
66
const findPosAndDir = (map) => map.flatMap((r, y) => r.flatMap((c, x) => dirs[c] ? [x, y, c] : null).filter(p => p !== null));
77
const outOfBounds = (map, x, y) => x < 0 || x > map[0].length - 1 || y < 0 || y > map.length - 1;
88

9-
const patrol = (map, x, y, dir) => {
9+
const patrol = (map, obs) => {
10+
let [x, y, dir] = findPosAndDir(map);
1011
const route = [];
1112
while (true) {
1213
const posAndDir = `${x},${y} ${dir}`;
@@ -15,24 +16,22 @@ const patrol = (map, x, y, dir) => {
1516
const [dx, dy, rotate] = dirs[dir];
1617
const [nx, ny] = [x + dx, y + dy];
1718
if (outOfBounds(map, nx, ny)) return route;
18-
if (map[ny][nx] == '#') dir = rotate;
19+
if (map[ny][nx] == '#' || (obs?.x == nx && obs?.y == ny)) dir = rotate;
1920
else [x, y] = [nx, ny];
2021
}
2122
}
2223

23-
const [startx, starty, startdir] = findPosAndDir(map);
24-
const route = patrol(map, startx, starty, startdir);
24+
const route = patrol(map);
2525
const positions = route.map(posAndDir => posAndDir.split(' ')[0]);
2626
const uniqPositions = [...new Set(positions)];
2727
console.log(`day6a: ${uniqPositions.length}`);
2828

29+
const firstPosition = positions[0];
2930
// try adding obstacle to visited position on route and check for loop
3031
const loop = uniqPositions.filter(pos => {
32+
if (pos == firstPosition) return false; // not allowed to add obstacle to start
3133
const [x, y] = pos.split(',').map(Number);
32-
if (x == startx && y == starty) return false; // not allowed to add obstacle to start
33-
const nmap = JSON.parse(JSON.stringify(map)); // deep clone
34-
nmap[y][x] = '#'; // add new obstacle
35-
return patrol(nmap, startx, starty, startdir) == null; //
34+
return patrol(map, {x, y}) == null; // patrol returns null in case of loop
3635
});
3736
const uniqLoop = new Set(loop);
3837
console.log(`day6b: ${uniqLoop.size}`);

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy