diff --git a/2023/02-cube-conundrum/src/main.rs b/2023/02-cube-conundrum/src/main.rs index d52adb4..e072d03 100644 --- a/2023/02-cube-conundrum/src/main.rs +++ b/2023/02-cube-conundrum/src/main.rs @@ -1,5 +1,7 @@ mod part_one; +mod part_two; fn main() { - part_one::part_one(); + //part_one::part_one(); + part_two::part_two(); } diff --git a/2023/02-cube-conundrum/src/part_two.rs b/2023/02-cube-conundrum/src/part_two.rs new file mode 100644 index 0000000..c85f295 --- /dev/null +++ b/2023/02-cube-conundrum/src/part_two.rs @@ -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

(filename: P) -> io::Result>> +where P: AsRef, { + 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::>()[1].parse::().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::().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; + +} \ No newline at end of file