Skip to content

Commit b76cfaf

Browse files
committed
refactor
1 parent 9e08994 commit b76cfaf

File tree

1 file changed

+22
-39
lines changed

1 file changed

+22
-39
lines changed

src/2025/day01.js

Lines changed: 22 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,48 +1,31 @@
1+
function parse(input) {
2+
return input.split("\n").map(x => {
3+
let [, direction, count] = x.match(/(L|R)(\d+)/);
4+
return { direction: direction === "L" ? -1 : 1, count: +count };
5+
});
6+
}
7+
18
export function part1(input) {
29
let password = 0;
3-
input
4-
.split("\n")
5-
.map(x => {
6-
let [, direction, count] = x.match(/(L|R)(\d+)/);
7-
return { direction, count: +count };
8-
})
9-
.reduce((prev, curr) => {
10-
if (curr.direction === "L") prev -= curr.count;
11-
if (curr.direction === "R") prev += curr.count;
12-
while (prev < 0) prev += 100;
13-
while (prev >= 100) prev -= 100;
14-
if (prev === 0) password++;
15-
return prev;
16-
}, 50);
17-
10+
parse(input).reduce((prev, curr) => {
11+
let next = (prev + curr.direction * curr.count) % 100;
12+
if (next < 0) next += 100;
13+
if (next === 0) password++;
14+
return next;
15+
}, 50);
1816
return password;
1917
}
2018

2119
export function part2(input) {
2220
let password = 0;
23-
input
24-
.split("\n")
25-
.map(x => {
26-
let [, direction, count] = x.match(/(L|R)(\d+)/);
27-
return { direction, count: +count };
28-
})
29-
.reduce((prev, curr) => {
30-
if (curr.direction === "L") {
31-
for (let i = 0; i < curr.count; i++) {
32-
prev--;
33-
if (prev === 0) password++;
34-
if (prev === -1) prev = 99;
35-
}
36-
}
37-
if (curr.direction === "R") {
38-
for (let i = 0; i < curr.count; i++) {
39-
prev++;
40-
if (prev === 100) prev = 0;
41-
if (prev === 0) password++;
42-
}
43-
}
44-
return prev;
45-
}, 50);
46-
21+
parse(input).reduce((prev, curr) => {
22+
for (let i = 0; i < curr.count; i++) {
23+
prev += curr.direction;
24+
if (prev === -1) prev = 99;
25+
if (prev === 100) prev = 0;
26+
if (prev === 0) password++;
27+
}
28+
return prev;
29+
}, 50);
4730
return password;
4831
}

0 commit comments

Comments
 (0)