advent-of-code/src/year_2023/day_02_cube_conundrum/part_two.rs

74 lines
1.6 KiB
Rust

use std::cmp::max;
use crate::utils::input_reader;
struct Game {
red: u32,
green: u32,
blue: u32,
}
pub fn part_two() {
if let Ok(lines) = input_reader::read_lines("./input.txt") {
let mut result = 0;
for line in lines {
result += process_line(&line.unwrap());
}
println!("{}", result);
}
}
fn process_line(s: &str) -> u32 {
let v: Vec<&str> = s.split(':').collect();
let game_id: u32 = v[0].split("Game ").collect::<Vec<&str>>()[1]
.parse::<u32>()
.unwrap();
let games: Vec<&str> = v[1].split(';').collect();
let mut min_game = Game {
red: 0,
green: 0,
blue: 0,
};
for game in games {
let game = process_game(game);
min_game.red = max(min_game.red, game.red);
min_game.green = max(min_game.green, game.green);
min_game.blue = max(min_game.blue, game.blue);
}
return min_game.red * min_game.green * min_game.blue;
}
fn process_game(s: &str) -> Game {
let mut game = Game {
red: 0,
green: 0,
blue: 0,
};
let cubes: Vec<&str> = s.split(',').collect();
for cube in cubes {
let cube_parts: Vec<&str> = cube.trim().split(' ').collect();
let cube_num = cube_parts[0].parse::<u32>().unwrap();
if cube_parts[1] == "red" {
game.red = cube_num;
} else if cube_parts[1] == "green" {
game.green = cube_num;
} else if cube_parts[1] == "blue" {
game.blue = cube_num;
}
}
return game;
}