From 46cee023d2c7473095b65a543076cc1d40d9ab80 Mon Sep 17 00:00:00 2001 From: "Adam T. Carpenter" Date: Mon, 4 Dec 2023 13:51:38 +0000 Subject: chore: common repo chore: break out part a chore: refactor to include b mode flag finish day 2 ignore --- aoc02/src/main.rs | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 aoc02/src/main.rs (limited to 'aoc02/src') diff --git a/aoc02/src/main.rs b/aoc02/src/main.rs new file mode 100644 index 0000000..b8b5eae --- /dev/null +++ b/aoc02/src/main.rs @@ -0,0 +1,53 @@ +use std::{collections::BTreeMap, env::args, io::stdin}; + +fn rounds_are_possible(rounds: &str) -> bool { + !rounds + .split(&[';', ',']) + .map(|round| round.trim().split_once(' ').expect("bad input whitespace")) + .map(|(score, color)| (score.parse::().expect("input score not digit"), color)) + .map(|(score, color)| { + color == "red" && score > 12 + || color == "blue" && score > 14 + || color == "green" && score > 13 + }) + .any(|p| p) +} + +fn rounds_power(rounds: &str) -> u32 { + let mut maximums = BTreeMap::new(); + + for (score, color) in rounds + .split(&[';', ',']) + .map(|round| round.trim().split_once(' ').expect("bad input whitespace")) + .map(|(score, color)| (score.parse::().expect("input score not digit"), color)) + { + if &score > maximums.get(color).unwrap_or(&0) { + maximums.insert(color, score); + } + } + + maximums.values().product() +} + +fn main() { + let b_mode = args().any(|b| b == "-b"); + let mut lines = stdin().lines(); + let mut possibilities = Vec::new(); + + while let Some(Ok(line)) = lines.next() { + let line = line + .strip_prefix("Game ") + .expect("input missing game prefix"); + let (id, rounds) = line + .split_once(": ") + .expect("input missing colon separator"); + + if !b_mode && rounds_are_possible(rounds) { + possibilities.push(id.parse::().expect("input id not integers")); + } else if b_mode { + possibilities.push(rounds_power(rounds)); + } + } + + println!("{}", possibilities.iter().sum::()); +} -- cgit v1.2.3