From 505121e9e3acb6b62b514c95fa959e729e31679b Mon Sep 17 00:00:00 2001 From: Zynh0722 Date: Fri, 1 Dec 2023 22:09:04 -0800 Subject: [PATCH] day two part two --- two/output-two | 1 + two/src/{main.rs => one.rs} | 0 two/src/two.rs | 75 +++++++++++++++++++++++++++++++++++++ 3 files changed, 76 insertions(+) create mode 100644 two/output-two rename two/src/{main.rs => one.rs} (100%) create mode 100644 two/src/two.rs diff --git a/two/output-two b/two/output-two new file mode 100644 index 0000000..e468195 --- /dev/null +++ b/two/output-two @@ -0,0 +1 @@ +70265 \ No newline at end of file diff --git a/two/src/main.rs b/two/src/one.rs similarity index 100% rename from two/src/main.rs rename to two/src/one.rs diff --git a/two/src/two.rs b/two/src/two.rs new file mode 100644 index 0000000..6a74d80 --- /dev/null +++ b/two/src/two.rs @@ -0,0 +1,75 @@ +use std::io::{self, Read}; + +#[derive(Debug)] +struct Game { + #[allow(unused)] + id: u32, + matches: Vec, +} + +impl Game { + fn min_match(&self) -> Match { + self.matches.iter().fold(Match(0, 0, 0), |acc, m| { + let mut red = acc.0; + let mut green = acc.1; + let mut blue = acc.2; + + if m.0 > red { + red = m.0; + } + if m.1 > green { + green = m.1; + } + if m.2 > blue { + blue = m.2; + } + + Match(red, green, blue) + }) + } +} + +#[derive(Debug)] +struct Match(u32, u32, u32); + +impl Match { + fn power(&self) -> u32 { + self.0 * self.1 * self.2 + } +} + +fn main() { + let mut buf = String::new(); + io::stdin().read_to_string(&mut buf).unwrap(); + + let lines: Vec = buf.lines().map(ToOwned::to_owned).collect(); + + let answer: u32 = lines + .iter() + .map(|l| &l[4..]) + .map(|l| l.split(':').map(str::trim).collect::>()) + .map(|l| Game { + id: l[0].parse().unwrap(), + matches: l[1] + .split(';') + .map(str::trim) + .map(|round| { + round + .split(',') + .map(str::trim) + .map(|cubes| cubes.split(' ').collect::>()) + .fold(Match(0, 0, 0), |acc, cube_count| match cube_count[1] { + "red" => Match(cube_count[0].parse().unwrap(), acc.1, acc.2), + "green" => Match(acc.0, cube_count[0].parse().unwrap(), acc.2), + "blue" => Match(acc.0, acc.1, cube_count[0].parse().unwrap()), + _ => acc, + }) + }) + .collect(), + }) + .map(|g| g.min_match()) + .map(|m| m.power()) + .sum(); + + print!("{answer}") +}