day 2 part 2
This commit is contained in:
parent
dcb65c8da2
commit
6a74138d9e
1 changed files with 5 additions and 14 deletions
19
src/main.rs
19
src/main.rs
|
@ -3,37 +3,28 @@ use fancy_regex::Regex;
|
||||||
use std::{collections::HashMap, io::stdin};
|
use std::{collections::HashMap, io::stdin};
|
||||||
|
|
||||||
fn main() -> Result<()> {
|
fn main() -> Result<()> {
|
||||||
// let input = File::open("input.txt")?;
|
|
||||||
// let reader = BufReader::new(input);
|
|
||||||
|
|
||||||
let game_re = Regex::new(r"Game (\d+): (.+)")?;
|
let game_re = Regex::new(r"Game (\d+): (.+)")?;
|
||||||
let cube_re = Regex::new(r"(\d+) (blue|red|green)")?;
|
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;
|
let mut sum = 0;
|
||||||
for line in stdin().lines() {
|
for line in stdin().lines() {
|
||||||
let line = line?;
|
let line = line?;
|
||||||
let c = game_re.captures(&line)?.unwrap();
|
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();
|
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 round in desc.split(';') {
|
||||||
for cube in cube_re.captures_iter(round) {
|
for cube in cube_re.captures_iter(round) {
|
||||||
let cube = cube?;
|
let cube = cube?;
|
||||||
let count: i32 = cube.get(1).unwrap().as_str().parse()?;
|
let count: i32 = cube.get(1).unwrap().as_str().parse()?;
|
||||||
let color = cube.get(2).unwrap().as_str();
|
let color = cube.get(2).unwrap().as_str();
|
||||||
println!("count={count} color={color}");
|
|
||||||
|
|
||||||
if count > *max_colors.get(&color).unwrap() {
|
let n = max_colors.get(&color).unwrap();
|
||||||
valid = false;
|
max_colors.insert(color, i32::max(*n, count));
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if valid {
|
let power: i32 = max_colors.values().product();
|
||||||
sum += game_number;
|
sum += power;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
println!("{sum}");
|
println!("{sum}");
|
||||||
|
|
Loading…
Reference in a new issue