summaryrefslogtreecommitdiff
path: root/2023/src/bin/day_3.rs
blob: 06e1300d2f105d042eee48d0f85d43f2a7f09464 (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
use nom::{
    branch::alt,
    bytes::complete::tag,
    character::complete::{digit1, line_ending, none_of},
    combinator::{map, map_res},
    multi::{many1, separated_list1},
    IResult,
};
use std::fs;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let input = fs::read_to_string("inputs/day_3.txt")?;
    let parsed = PartInventory::parser(&input).unwrap().1;
    dbg!(&parsed.part_number_sum());
    dbg!(&parsed.gear_ratio_sum());

    Ok(())
}

#[derive(Debug)]
struct PartInventory {
    parts: Vec<Part>,
    symbols: Vec<Symbol>,
}

#[derive(Debug)]
struct Part {
    number: u32,
    symbols: Vec<char>,
    y: usize,
    min_x: usize,
    max_x: usize,
}

#[derive(Debug, Clone)]
struct Symbol {
    symbol: char,
    parts: Vec<u32>,
    x: usize,
    y: usize,
}

#[derive(Debug)]
enum LexToken {
    Space(usize),
    Part(usize, u32),
    Symbol(char),
}

impl PartInventory {
    fn parser(input: &str) -> IResult<&str, Self> {
        map(LexToken::parser, |tokens| {
            let mut parts = Vec::new();
            let mut symbols = Vec::new();

            for (y, row) in tokens.iter().enumerate() {
                let mut x = 0;
                for token in row {
                    match token {
                        LexToken::Space(_) => {}
                        LexToken::Part(len, number) => parts.push(Part {
                            number: *number,
                            symbols: Vec::new(),
                            y,
                            min_x: x,
                            max_x: x + len - 1,
                        }),
                        LexToken::Symbol(symbol) => symbols.push(Symbol {
                            symbol: *symbol,
                            parts: Vec::new(),
                            y,
                            x,
                        }),
                    }
                    x += token.len();
                }
            }

            for part in &mut parts {
                part.symbols = symbols
                    .iter()
                    .filter(|symbol| part.touches(symbol))
                    .map(|symbol| symbol.symbol)
                    .collect();
            }

            for symbol in &mut symbols {
                symbol.parts = parts
                    .iter()
                    .filter(|part| part.touches(symbol))
                    .map(|part| part.number)
                    .collect();
            }

            PartInventory { parts, symbols }
        })(input)
    }

    fn part_number_sum(&self) -> u32 {
        self.parts
            .iter()
            .filter(|part| part.symbols.len() > 0)
            .map(|part| part.number)
            .sum()
    }

    fn gear_ratio_sum(&self) -> u32 {
        self.symbols
            .iter()
            .filter(|symbol| symbol.symbol == '*' && symbol.parts.len() == 2)
            .map(|symbol| symbol.parts[0] * symbol.parts[1])
            .sum()
    }
}

impl LexToken {
    fn parser(input: &str) -> IResult<&str, Vec<Vec<Self>>> {
        separated_list1(
            line_ending,
            many1(alt((
                map(many1(tag(".")), |dots| LexToken::Space(dots.len())),
                map_res(digit1, |num_s: &str| {
                    num_s
                        .parse()
                        .map(|num_i| LexToken::Part(num_s.len(), num_i))
                }),
                map(none_of("\n"), |s| LexToken::Symbol(s)),
            ))),
        )(input)
    }

    fn len(&self) -> usize {
        match self {
            Self::Space(len) => *len,
            Self::Part(len, _) => *len,
            Self::Symbol(_) => 1,
        }
    }
}

impl Part {
    fn touches(&self, symbol: &Symbol) -> bool {
        let part = self;
        symbol.x >= part.min_x.saturating_sub(1)
            && symbol.x <= part.max_x.saturating_add(1)
            && symbol.y >= part.y.saturating_sub(1)
            && symbol.y <= part.y.saturating_add(1)
    }
}