diff --git a/src/bin/d21p1.rs b/src/bin/d21p1.rs new file mode 100644 index 0000000..7364953 --- /dev/null +++ b/src/bin/d21p1.rs @@ -0,0 +1,7 @@ +use aoc22::{day21, util}; + +pub fn main() { + let monkeys = day21::parse_monkeys(&util::parse_input()); + + println!("root yells: {}", day21::yell(&monkeys, "root")); +} diff --git a/src/day21.rs b/src/day21.rs new file mode 100644 index 0000000..537823c --- /dev/null +++ b/src/day21.rs @@ -0,0 +1,64 @@ +use std::collections::HashMap; + +use regex::Regex; + +#[derive(Debug)] +pub enum Operation { + Add, + Sub, + Mul, + Div, +} + +impl Operation { + pub fn from(s: &str) -> Operation { + match s { + "+" => Operation::Add, + "-" => Operation::Sub, + "*" => Operation::Mul, + "/" => Operation::Div, + _ => panic!("Unknown operation {}", s), + } + } +} + +#[derive(Debug)] +pub enum Monkey { + Number(isize), + Calculate(String, String, Operation), +} + +pub fn parse_monkeys(input: &String) -> HashMap { + let mut result = HashMap::new(); + + let re = Regex::new(r"^(\w+): (?:(\d+)|(\w+) ([+\-*/]) (\w+))$").unwrap(); + for line in input.lines() { + let captures = re.captures(line).unwrap(); + let name = captures.get(1).unwrap().as_str(); + let monkey = if let Some(num) = captures.get(2) { + Monkey::Number(num.as_str().parse().unwrap()) + } else { + Monkey::Calculate( + captures.get(3).unwrap().as_str().to_owned(), + captures.get(5).unwrap().as_str().to_owned(), + Operation::from(captures.get(4).unwrap().as_str()), + ) + }; + result.insert(name.to_owned(), monkey); + } + + result +} + +pub fn yell(monkeys: &HashMap, monkey: &str) -> isize { + let monkey = &monkeys[monkey]; + match monkey { + Monkey::Number(n) => *n, + Monkey::Calculate(a, b, op) => match op { + Operation::Add => yell(monkeys, a) + yell(monkeys, b), + Operation::Sub => yell(monkeys, a) - yell(monkeys, b), + Operation::Mul => yell(monkeys, a) * yell(monkeys, b), + Operation::Div => yell(monkeys, a) / yell(monkeys, b), + }, + } +} diff --git a/src/lib.rs b/src/lib.rs index e63c09b..7658860 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -11,6 +11,7 @@ pub mod day18; pub mod day19; pub mod day2; pub mod day20; +pub mod day21; pub mod day3; pub mod day4; pub mod day5;