|
| 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 | + |
1 | 8 | export function part1(input) { |
2 | 9 | 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); |
18 | 16 | return password; |
19 | 17 | } |
20 | 18 |
|
21 | 19 | export function part2(input) { |
22 | 20 | 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); |
47 | 30 | return password; |
48 | 31 | } |
0 commit comments