Skip to main content

year2024/
day25.rs

1use utils::prelude::*;
2
3/// Finding matching keys and locks.
4#[derive(Clone, Debug)]
5pub struct Day25 {
6    locks: Vec<u32>,
7    keys: Vec<u32>,
8}
9
10impl Day25 {
11    pub fn new(input: &str, _: InputType) -> Result<Self, InputError> {
12        let mut locks = Vec::with_capacity(250);
13        let mut keys = Vec::with_capacity(250);
14
15        for item in parser::bitmask_n::<5, u32>(b".#")
16            .repeat_n::<7, _>(parser::eol())
17            .with_consumed()
18            .with_eol()
19            .with_eol()
20            .parse_iterator(input)
21        {
22            let (rows, grid_str) = item?;
23
24            let [top, .., bottom] = rows;
25            if !matches!((top, bottom), (0b11111, 0) | (0, 0b11111)) {
26                return Err(InputError::new(input, grid_str, "expected lock or key"));
27            }
28
29            let mask = rows[1..6]
30                .iter()
31                .enumerate()
32                .fold(0, |acc, (i, &row)| acc | row << (i * 5));
33
34            if top != 0 {
35                locks.push(mask);
36            } else {
37                keys.push(mask);
38            }
39        }
40
41        Ok(Self { locks, keys })
42    }
43
44    #[must_use]
45    pub fn part1(&self) -> u32 {
46        let mut total = 0;
47        for &lock in &self.locks {
48            for &key in &self.keys {
49                if lock & key == 0 {
50                    total += 1;
51                }
52            }
53        }
54        total
55    }
56
57    #[must_use]
58    pub fn part2(&self) -> &'static str {
59        "🎄"
60    }
61}
62
63examples!(Day25 -> (u32, &'static str) [
64    {file: "day25_example0.txt", part1: 3},
65]);