Add src/02part2.rs

This commit is contained in:
Cassandra de la Cruz-Munoz 2023-12-05 21:34:54 +01:00
parent 615e4b9c68
commit ef37c4c19f

96
src/02part2.rs Normal file
View File

@ -0,0 +1,96 @@
use std::fs;
use regex::Regex;
use std::cmp;
fn main() {
let file_path = "input/02input.txt";
let contents = fs::read_to_string(file_path).expect("should read file");
let lines = contents.lines();
let re = Regex::new(r"((((?<blue_a>\d+) blue)|((?<green_a>\d+) green)|((?<red_a>\d+) red)), ){0,2}(((?<blue_b>\d+) blue)|((?<green_b>\d+) green)|((?<red_b>\d+) red))").unwrap();
println!("{:?}", re.capture_names());
let mut sum = 0;
for line in lines {
let mut line_split = line.split(':');
let mut game_num = 0;
match line_split.next() {
Some(l) => {
match l[5 .. l.len()].parse::<u32>().ok() {
Some(n) => {game_num = n},
None => break,
}
},
None => break,
}
let mut valid = true;
let mut has_next = true;
let mut plays = line_split.next().unwrap().split(";");
let mut caps = re.captures(plays.next().unwrap()).unwrap();
let mut min_red = 0;
let mut min_green = 0;
let mut min_blue = 0;
while valid && has_next {
let mut blue: u32 = 0;
let mut red: u32 = 0;
let mut green: u32 = 0;
match caps.name("blue_b") {
Some(m) => {
blue = m.as_str().parse::<u32>().ok().unwrap();
match caps.name("green_a") {
Some(g) => {green = g.as_str().parse::<u32>().ok().unwrap();},
None => {},
}
match caps.name("red_a") {
Some(r) => {red = r.as_str().parse::<u32>().ok().unwrap();},
None => {},
}
},
None => {
match caps.name("green_b") {
Some(m) => {
green = m.as_str().parse::<u32>().ok().unwrap();
match caps.name("blue_a") {
Some(b) => {blue = b.as_str().parse::<u32>().ok().unwrap();},
None => {},
}
match caps.name("red_a") {
Some(r) => {red = r.as_str().parse::<u32>().ok().unwrap();},
None => {},
}
},
None => {
match caps.name("red_b") {
Some(m) => {
red = m.as_str().parse::<u32>().ok().unwrap();
match caps.name("blue_a") {
Some(b) => {blue = b.as_str().parse::<u32>().ok().unwrap();},
None => {},
}
match caps.name("green_a") {
Some(g) => {green = g.as_str().parse::<u32>().ok().unwrap();},
None => {},
}
},
None => {},
}
}
}
}
}
println!("{} {} {}", red, blue, green);
min_red = cmp::max(min_red, red);
min_blue = cmp::max(min_blue, blue);
min_green = cmp::max(min_green, green);
// if red > 12 || blue > 14 || green > 13 {
// valid = false;
match plays.next() {
Some(l) => {caps = re.captures(l).unwrap()},
None => {has_next = false},
}
}
sum += min_red * min_blue * min_green;
// if valid {
// sum += game_num;
// }
}
println!("{}", sum);
}