Day 21, part 1
This commit is contained in:
parent
93f574463b
commit
9b42768fdb
|
@ -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"));
|
||||
}
|
|
@ -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<String, Monkey> {
|
||||
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<String, Monkey>, 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),
|
||||
},
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
|
|
Loading…
Reference in New Issue