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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
/* Copyright 2023 Mario Finelli
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

//! Advent of Code 2023 Day 2: <https://adventofcode.com/2023/day/2>
//!
//! Today's challenge was fairly easy, the most challenging part was parsing
//! the input (which was straightforward with a few simple regular
//! expressions).

use regex::Regex;
use std::collections::BinaryHeap;

/// Draw repredents a handful of cubes in a game. Each color (red, blue, and
/// green) can have some or none.
#[derive(Debug)]
struct Draw {
    red: Option<u32>,
    blue: Option<u32>,
    green: Option<u32>,
}

/// Game represents each game from the input, it has a number and a variable
/// number of draws.
#[derive(Debug)]
struct Game {
    number: u32,
    draws: Vec<Draw>,
}

/// The solution for the day two challenge.
///
/// As usual, we take the input as a string and an integer denoting the part of
/// the problem that we want to solve. In part `1` we return the sum of the
/// game numbers of the games that are possible, and in part `2` we instead
/// return the sum of the "powers" of the games (more information about how to
/// compute the power is in the prompt but basically the minimum number of
/// red, blue, and green cubes multiplies together). After we parse the input
/// we switch on the part and either check if the game is possible and add its
/// number to the sum or compute its power and add it to the sum.
///
/// # Example
/// ```rust
/// # use aoc::y23d02::y23d02;
/// // probably read this from the input file...
/// let input = concat!(
///     "Game 1: 20 red, 20 blue, 20 green\n",
///     "Game 2: 5 red, 5 blue, 5 green",
/// );
/// assert_eq!(y23d02(input, 1), 2);
/// assert_eq!(y23d02(input, 2), 8125);
/// ```
pub fn y23d02(input: &str, part: u32) -> u32 {
    let mut sum = 0;
    let mut games = Vec::new();
    let red_regex = Regex::new(r"(\d+) red").unwrap();
    let blue_regex = Regex::new(r"(\d+) blue").unwrap();
    let green_regex = Regex::new(r"(\d+) green").unwrap();

    for line in input.lines() {
        let parts: Vec<_> = line.split(": ").collect();
        let number = parts[0].split_whitespace().collect::<Vec<_>>()[1]
            .parse()
            .unwrap();
        let mut draws = Vec::new();

        for d in parts[1].split("; ") {
            let mut draw = Draw {
                red: None,
                blue: None,
                green: None,
            };

            if let Some(r) = red_regex.captures(d) {
                draw.red = Some(r[1].parse().unwrap());
            }

            if let Some(b) = blue_regex.captures(d) {
                draw.blue = Some(b[1].parse().unwrap());
            }

            if let Some(g) = green_regex.captures(d) {
                draw.green = Some(g[1].parse().unwrap());
            }

            draws.push(draw);
        }

        games.push(Game { number, draws });
    }

    if part == 1 {
        for game in games {
            if is_possible(&game) {
                sum += game.number;
            }
        }
    } else {
        for game in games {
            sum += compute_power(&game);
        }
    }

    sum
}

/// This function computes if a game is possible given the constraint on the
/// number of red, blue, and green cubes as specified in the prompt.
fn is_possible(game: &Game) -> bool {
    let red = 12;
    let blue = 14;
    let green = 13;

    for draw in &game.draws {
        if let Some(r) = draw.red {
            if r > red {
                return false;
            }
        }

        if let Some(b) = draw.blue {
            if b > blue {
                return false;
            }
        }

        if let Some(g) = draw.green {
            if g > green {
                return false;
            }
        }
    }

    true
}

/// This function computes the power of a game. We use a
/// [`std::collections::BinaryHeap`] to keep track of the minimum number of
/// cube for each game across all draws and pop the heap for each cube to
/// compute the power.
fn compute_power(game: &Game) -> u32 {
    let mut red = BinaryHeap::from([0]);
    let mut blue = BinaryHeap::from([0]);
    let mut green = BinaryHeap::from([0]);

    for draw in &game.draws {
        if let Some(r) = draw.red {
            red.push(r);
        }

        if let Some(b) = draw.blue {
            blue.push(b);
        }

        if let Some(g) = draw.green {
            green.push(g);
        }
    }

    red.pop().unwrap() * blue.pop().unwrap() * green.pop().unwrap()
}

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

    #[test]
    fn test_is_possible() {
        let game = Game {
            number: 1,
            draws: vec![
                Draw {
                    red: Some(4),
                    blue: Some(3),
                    green: None,
                },
                Draw {
                    red: Some(1),
                    blue: Some(6),
                    green: Some(2),
                },
                Draw {
                    red: None,
                    blue: None,
                    green: Some(2),
                },
            ],
        };

        assert!(is_possible(&game));

        let game = Game {
            number: 2,
            draws: vec![
                Draw {
                    red: None,
                    blue: Some(1),
                    green: Some(2),
                },
                Draw {
                    red: Some(1),
                    blue: Some(4),
                    green: Some(3),
                },
                Draw {
                    red: None,
                    blue: Some(1),
                    green: Some(1),
                },
            ],
        };

        assert!(is_possible(&game));

        let game = Game {
            number: 3,
            draws: vec![
                Draw {
                    red: Some(20),
                    blue: Some(6),
                    green: Some(8),
                },
                Draw {
                    red: Some(4),
                    blue: Some(5),
                    green: None,
                },
                Draw {
                    red: None,
                    blue: None,
                    green: Some(13),
                },
                Draw {
                    red: Some(1),
                    blue: None,
                    green: Some(5),
                },
            ],
        };

        assert!(!is_possible(&game));
    }

    #[test]
    fn test_compute_power() {
        let game = Game {
            number: 1,
            draws: vec![
                Draw {
                    red: Some(4),
                    blue: Some(3),
                    green: None,
                },
                Draw {
                    red: Some(1),
                    blue: Some(6),
                    green: Some(2),
                },
                Draw {
                    red: None,
                    blue: None,
                    green: Some(2),
                },
            ],
        };

        assert_eq!(compute_power(&game), 48);

        let game = Game {
            number: 2,
            draws: vec![
                Draw {
                    red: None,
                    blue: Some(1),
                    green: Some(2),
                },
                Draw {
                    red: Some(1),
                    blue: Some(4),
                    green: Some(3),
                },
                Draw {
                    red: None,
                    blue: Some(1),
                    green: Some(1),
                },
            ],
        };

        assert_eq!(compute_power(&game), 12);

        let game = Game {
            number: 3,
            draws: vec![
                Draw {
                    red: Some(20),
                    blue: Some(6),
                    green: Some(8),
                },
                Draw {
                    red: Some(4),
                    blue: Some(5),
                    green: None,
                },
                Draw {
                    red: None,
                    blue: None,
                    green: Some(13),
                },
                Draw {
                    red: Some(1),
                    blue: None,
                    green: Some(5),
                },
            ],
        };

        assert_eq!(compute_power(&game), 1560);
    }

    #[test]
    fn it_works() {
        let input = concat!(
            "Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green\n",
            "Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, ",
            "1 blue\n",
            "Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; ",
            "5 green, 1 red\n",
            "Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 ",
            "blue, 14 red\n",
            "Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green\n",
        );

        assert_eq!(y23d02(input, 1), 8);
        assert_eq!(y23d02(input, 2), 2286);
    }

    #[test]
    fn the_solution() {
        let contents = fs::read_to_string("input/2023/day02.txt").unwrap();

        assert_eq!(y23d02(&contents, 1), 2551);
        assert_eq!(y23d02(&contents, 2), 62811);
    }
}