aboutsummaryrefslogtreecommitdiff
path: root/day1/src/main.rs
blob: 50ab8e13b95091cc0b22a7815a760410ae8c2010 (plain)
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
use anyhow::anyhow;
use std::{
    env, fs,
    ops::{Add, Sub},
    str::FromStr,
};

#[derive(Debug, PartialEq, Eq)]
enum Rotation {
    Left(u32),
    Right(u32),
}

#[derive(Debug)]
struct ParseRotationError;

impl FromStr for Rotation {
    type Err = ParseRotationError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut chars = s.chars();
        let lr = chars.next().ok_or(ParseRotationError)?;
        let n: u32 = chars
            .collect::<String>()
            .parse()
            .map_err(|_| ParseRotationError)?;

        match lr {
            'L' => Ok(Self::Left(n)),
            'R' => Ok(Self::Right(n)),
            _ => Err(ParseRotationError),
        }
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
struct Dial(u8);

struct RotateResult(u32, Dial);

impl Dial {
    fn rotate(self, rot: &Rotation) -> RotateResult {
        let pos = self.0 as u32;

        match rot {
            Rotation::Left(n) => {
                if pos != 0 && *n >= pos {
                    let quot = n.div_ceil(100);
                    RotateResult(quot, self - *n)
                } else {
                    RotateResult(0, self - *n)
                }
            }

            Rotation::Right(n) => {
                if n + pos >= 100 {
                    let quot = n.div_ceil(100);
                    RotateResult(quot, self + *n)
                } else {
                    RotateResult(0, self + *n)
                }
            }
        }
    }
}

impl From<u8> for Dial {
    fn from(value: u8) -> Self {
        Self(value)
    }
}

impl Add<u32> for Dial {
    type Output = Self;

    fn add(self, rhs: u32) -> Self::Output {
        let n = self.0 as u32;
        let m = (n + rhs) % 100;
        Self(m as u8)
    }
}

impl Sub<u32> for Dial {
    type Output = Self;

    fn sub(self, rhs: u32) -> Self::Output {
        let n = self.0 as u32;
        let m = (n + 100 - rhs % 100) % 100;
        Self(m as u8)
    }
}

impl PartialEq<u8> for Dial {
    fn eq(&self, other: &u8) -> bool {
        self.0 == *other
    }
}

fn main() -> anyhow::Result<()> {
    let mut args = env::args();
    let input_path = args.nth(1).ok_or_else(|| anyhow!("usage: day1 INPUT"))?;
    let input = fs::read_to_string(input_path)?;

    let rotations: Vec<Rotation> = input
        .split_whitespace()
        .map(|s| s.parse().map_err(|_| anyhow!("bad rotation: {}", s)))
        .collect::<anyhow::Result<_>>()?;

    let mut dial = Dial::from(50);
    let mut exact_zeros = 0;
    let mut total_zeros = 0;

    for rot in &rotations {
        let RotateResult(zeros, new_dial) = dial.rotate(rot);

        if new_dial == 0 {
            exact_zeros += 1;
        }

        total_zeros += zeros;
        dial = new_dial;
    }

    println!("Password: {}", exact_zeros);
    println!("Password (method 0x434C49434B): {}", total_zeros);

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_rotation() {
        assert!("L2"
            .parse::<Rotation>()
            .is_ok_and(|rot| rot == Rotation::Left(2)));

        assert!("R929"
            .parse::<Rotation>()
            .is_ok_and(|rot| rot == Rotation::Right(929)));

        assert!("M1".parse::<Rotation>().is_err());
        assert!("L".parse::<Rotation>().is_err());
        assert!("2".parse::<Rotation>().is_err());
    }

    #[test]
    fn dial_ops() {
        let dial = Dial::from(50);

        assert_eq!(dial + 1, 51);
        assert_eq!(dial + 50, 0);
        assert_eq!(dial + 100, 50);
        assert_eq!(dial + 150, 0);
        assert_eq!(dial + 2 + 48, 0);
        assert_eq!(dial + 45 + 60, 55);

        assert_eq!(dial - 45, 5);
        assert_eq!(dial - 45 - 10, 95);
        assert_eq!(dial - 1, 49);
        assert_eq!(dial - 68, 82);
        assert_eq!(dial - 68 - 30, 52);
        assert_eq!(dial - 100, 50);
        assert_eq!(dial - 998, 52);
        assert_eq!(dial - 150, 0);
        assert_eq!(dial - 51, 99);
        assert_eq!(dial - 50, 0);
    }

    #[test]
    fn dial_rotate() {
        let mut dial = Dial::from(50);

        let rotations = vec![
            // Example data
            (Rotation::Left(68), 1, 82),
            (Rotation::Left(30), 0, 52),
            (Rotation::Right(48), 1, 0),
            (Rotation::Left(5), 0, 95),
            (Rotation::Right(60), 1, 55),
            (Rotation::Left(55), 1, 0),
            (Rotation::Left(1), 0, 99),
            (Rotation::Left(99), 1, 0),
            (Rotation::Right(14), 0, 14),
            (Rotation::Left(82), 1, 32),
            // Additional data
            (Rotation::Left(200), 2, 32),
            (Rotation::Right(200), 2, 32),
            (Rotation::Left(30), 0, 2),
            (Rotation::Left(10), 1, 92),
            (Rotation::Right(10), 1, 2),
            (Rotation::Left(110), 2, 92),
            (Rotation::Right(210), 3, 2),
            (Rotation::Right(48), 0, 50),
            (Rotation::Right(1000), 10, 50),
            (Rotation::Right(48), 0, 98),
            (Rotation::Left(651), 6, 47),
        ];

        for (rot, expected_zeros, expected_dial) in &rotations {
            let RotateResult(zeros, new_dial) = dial.rotate(rot);
            assert_eq!(&zeros, expected_zeros, "rotating with {:?}", rot);
            assert_eq!(&new_dial, expected_dial, "rotating with {:?}", rot);
            dial = new_dial;
        }
    }
}