1use utils::prelude::*;
2
3#[derive(Clone, Debug)]
5pub struct Day02<'a> {
6 input: &'a str,
7}
8
9impl<'a> Day02<'a> {
10 pub fn new(input: &'a str, _: InputType) -> Result<Self, InputError> {
11 if let Some(b) = input
12 .bytes()
13 .find(|b| !matches!(b, b'U' | b'D' | b'L' | b'R' | b'\n'))
14 {
15 return Err(InputError::new(
16 input,
17 b as char,
18 "expected U, D, L, R or newline",
19 ));
20 }
21
22 Ok(Self { input })
23 }
24
25 #[must_use]
26 pub fn part1(&self) -> String {
27 let mut num = 5;
28 let mut result = String::new();
29
30 for line in self.input.lines() {
31 for c in line.bytes() {
32 num = match (c, num) {
33 (b'U', 4..=9) => num - 3,
34 (b'D', 1..=6) => num + 3,
35 (b'L', 2..=3 | 5..=6 | 8..=9) => num - 1,
36 (b'R', 1..=2 | 4..=5 | 7..=8) => num + 1,
37 (_, _) => num,
38 };
39 }
40 result.push((b'0' + num) as char);
41 }
42
43 result
44 }
45
46 #[must_use]
47 pub fn part2(&self) -> String {
48 let mut num = 5;
49 let mut result = String::new();
50
51 for line in self.input.lines() {
52 for c in line.bytes() {
53 num = match (c, num) {
54 (b'U', 3) => 1,
55 (b'U', 6..=8 | 10..=12) => num - 4,
56 (b'U', 13) => 11,
57 (b'D', 1) => 3,
58 (b'D', 2..=4 | 6..=8) => num + 4,
59 (b'D', 11) => 13,
60 (b'L', 3..=4 | 6..=9 | 11..=12) => num - 1,
61 (b'R', 2..=3 | 5..=8 | 10..=11) => num + 1,
62 (_, _) => num,
63 };
64 }
65 result.push((if num >= 10 { b'A' - 10 } else { b'0' } + num) as char);
66 }
67
68 result
69 }
70}
71
72examples!(Day02<'_> -> (&'static str, &'static str) [
73 {input: "ULL\nRRDDD\nLURDL\nUUUUD", part1: "1985", part2: "5DB3"},
74]);