day 2 part 2

This commit is contained in:
Andy Teijelo 2023-12-02 00:54:39 -05:00
parent dcb65c8da2
commit 6a74138d9e

View file

@ -3,37 +3,28 @@ use fancy_regex::Regex;
use std::{collections::HashMap, io::stdin};
fn main() -> Result<()> {
// let input = File::open("input.txt")?;
// let reader = BufReader::new(input);
let game_re = Regex::new(r"Game (\d+): (.+)")?;
let cube_re = Regex::new(r"(\d+) (blue|red|green)")?;
let max_colors = HashMap::from([("red", 12), ("green", 13), ("blue", 14)]);
let mut sum = 0;
for line in stdin().lines() {
let line = line?;
let c = game_re.captures(&line)?.unwrap();
let game_number: i32 = c.get(1).unwrap().as_str().parse()?;
let desc = c.get(2).unwrap().as_str();
println!("game={game_number}");
let mut valid = true;
let mut max_colors = HashMap::from([("red", 0), ("green", 0), ("blue", 0)]);
for round in desc.split(';') {
for cube in cube_re.captures_iter(round) {
let cube = cube?;
let count: i32 = cube.get(1).unwrap().as_str().parse()?;
let color = cube.get(2).unwrap().as_str();
println!("count={count} color={color}");
if count > *max_colors.get(&color).unwrap() {
valid = false;
}
let n = max_colors.get(&color).unwrap();
max_colors.insert(color, i32::max(*n, count));
}
}
if valid {
sum += game_number;
}
let power: i32 = max_colors.values().product();
sum += power;
}
println!("{sum}");