2023-02: Implement part 2

This commit is contained in:
LordMathis 2023-12-02 23:45:06 +01:00
parent 16ab3b3b0b
commit 3fc02ca06b
2 changed files with 79 additions and 1 deletions

View File

@ -1,5 +1,7 @@
mod part_one;
mod part_two;
fn main() {
part_one::part_one();
//part_one::part_one();
part_two::part_two();
}

View File

@ -0,0 +1,76 @@
use std::fs::File;
use std::io::{self, BufRead};
use std::path::Path;
use std::cmp::max;
struct Game {
red: u32,
green: u32,
blue: u32
}
pub fn part_two() {
if let Ok(lines) = read_lines("./input.txt") {
let mut result = 0;
for line in lines {
result += process_line(&line.unwrap());
}
println!("{}", result);
}
}
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where P: AsRef<Path>, {
let file = File::open(filename)?;
Ok(io::BufReader::new(file).lines())
}
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;
}