solved problem 2, day 2

This commit is contained in:
Nickiel12 2023-12-02 11:54:14 -08:00
parent 6b65ce53d0
commit 55916f2c60

View file

@ -1,4 +1,62 @@
use std::fs;
pub fn part2() { 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;
} }