-
Notifications
You must be signed in to change notification settings - Fork 0
/
part1.ts
63 lines (56 loc) · 1.55 KB
/
part1.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import * as fs from 'fs';
const input = fs.readFileSync('input', 'utf8');
const DIRECTION_MAP = [
{ x: 1, y: 0 },
{ x: 0, y: 1 },
{ x: -1, y: 0 },
{ x: 0, y: -1 },
];
const walk = (pos: { x: number; y: number; direction: number }, steps: number) => {
for (; steps > 0; steps--) {
const heading = DIRECTION_MAP[pos.direction];
let next = { ...pos };
next.x += heading.x;
next.y += heading.y;
if (maze[next.y]?.[next.x] !== '.' && maze[next.y]?.[next.x] !== '#') {
next = wrap(pos);
}
if (maze[next.y][next.x] === '#') {
break;
}
pos = next;
}
return pos;
};
const wrap = (pos: { x: number; y: number; direction: number }) => {
const heading = DIRECTION_MAP[pos.direction];
const opposite = { x: heading.x * -1, y: heading.y * -1 };
const wrap = { ...pos };
while (
maze[wrap.y + opposite.y]?.[wrap.x + opposite.x] === '.' ||
maze[wrap.y + opposite.y]?.[wrap.x + opposite.x] === '#'
) {
wrap.x += opposite.x;
wrap.y += opposite.y;
}
return wrap;
};
let [maze, directions] = input.split('\n\n');
let pos = { x: 0, y: 0, direction: 0 };
maze = maze.split('\n');
directions = directions.replace(/(R|L)/g, ',$1,').split(',');
while (maze[pos.y][pos.x] !== '.') {
pos.x++;
}
while (directions.length > 0) {
const next = directions.shift();
if (next === 'R') {
pos.direction = (pos.direction + 1) % 4;
} else if (next === 'L') {
pos.direction = (4 + pos.direction - 1) % 4;
} else if (Number.isInteger(+next)) {
pos = walk(pos, +next);
}
}
const result = (pos.y + 1) * 1000 + (pos.x + 1) * 4 + pos.direction;
console.log(result);