From 55916f2c60112faabbd1895bb25fe2b24ba2f5ac Mon Sep 17 00:00:00 2001 From: Nickiel12 Date: Sat, 2 Dec 2023 11:54:14 -0800 Subject: [PATCH] solved problem 2, day 2 --- day2/src/part2.rs | 58 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/day2/src/part2.rs b/day2/src/part2.rs index 2930e0a..487ecdd 100644 --- a/day2/src/part2.rs +++ b/day2/src/part2.rs @@ -1,4 +1,62 @@ +use std::fs; pub fn part2() { + let file_contents = fs::read_to_string("./input.txt").unwrap(); + let sum: i64 = file_contents + .lines() + .map(|x| { + if x.len() > 1 { + get_game_power(x.get(x.find(':').unwrap()..).unwrap()) + } else { + 0 + } + }) + .sum(); + + println!("The sum of products is: {}", sum); +} + +fn get_game_power(input: &str) -> i64 { + + let mut max_red: i64 = 0; + let mut max_green: i64 = 0; + let mut max_blue: i64 = 0; + let mut cur_val: i64 = 0; + let mut prior_char: char = ' '; + + let _: Vec<_> = input.chars() + .map(|x| { + if x.is_digit(10) { + if prior_char.is_digit(10) { + cur_val = cur_val * 10 + x.to_digit(10).unwrap() as i64; + } else { + cur_val = x.to_digit(10).unwrap() as i64; + } + } + + if prior_char == ' ' && (x == 'r' || x == 'g' || x == 'b') { + match x { + 'r' => { + max_red = std::cmp::max(max_red, cur_val); + }, + 'g' => { + max_green = std::cmp::max(max_green, cur_val); + }, + 'b' => { + max_blue = std::cmp::max(max_blue, cur_val); + } + _ => { + + } + } + } + + prior_char = x; + + //ignore spaces + + }).collect(); + + return max_red * max_green * max_blue; }