Skip to content

Commit

Permalink
21: avoid allocations to string
Browse files Browse the repository at this point in the history
  • Loading branch information
AxlLind committed Dec 21, 2022
1 parent 74411c4 commit e25fe4d
Showing 1 changed file with 20 additions and 19 deletions.
39 changes: 20 additions & 19 deletions src/bin/21.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
use hashbrown::HashMap;
use itertools::Itertools;

enum Op {
enum Op<'a> {
Num(i64),
Add(String, String),
Sub(String, String),
Mul(String, String),
Div(String, String),
Add(&'a str, &'a str),
Sub(&'a str, &'a str),
Mul(&'a str, &'a str),
Div(&'a str, &'a str),
}

fn val(monkies: &HashMap<String, Op>, cache: &mut HashMap<String, i64>, name: &str) -> i64 {
fn val<'a>(monkies: &'a HashMap<&str, Op>, cache: &mut HashMap<&'a str, i64>, name: &'a str) -> i64 {
if let Some(&v) = cache.get(name) {
return v;
}
Expand All @@ -20,11 +20,14 @@ fn val(monkies: &HashMap<String, Op>, cache: &mut HashMap<String, i64>, name: &s
Op::Mul(m1, m2) => val(monkies, cache, &m1) * val(monkies, cache, &m2),
Op::Div(m1, m2) => val(monkies, cache, &m1) / val(monkies, cache, &m2),
};
cache.insert(name.to_string(), v);
cache.insert(name, v);
v
}

fn get_eq(monkies: &HashMap<String, Op>, name: &str) -> String {
fn get_eq(monkies: &HashMap<&str, Op>, name: &str) -> String {
if name == "humn" {
return "x".to_string();
}
match &monkies[name] {
Op::Num(i) => i.to_string(),
Op::Add(m1, m2) => format!("({} + {})", get_eq(monkies, &m1), get_eq(monkies, &m2)),
Expand All @@ -36,20 +39,18 @@ fn get_eq(monkies: &HashMap<String, Op>, name: &str) -> String {

#[aoc::main(21)]
fn main(input: &str) -> (i64, &str) {
let mut monkies = input.lines().map(|l| {
let monkies = input.lines().map(|l| {
let (name, rest) = l.split_once(": ").unwrap();
let op = match rest.split(' ').collect_tuple() {
Some((m1, "+", m2)) => Op::Add(m1.to_string(), m2.to_string()),
Some((m1, "-", m2)) => Op::Sub(m1.to_string(), m2.to_string()),
Some((m1, "*", m2)) => Op::Mul(m1.to_string(), m2.to_string()),
Some((m1, "/", m2)) => Op::Div(m1.to_string(), m2.to_string()),
Some((m1, "+", m2)) => Op::Add(m1, m2),
Some((m1, "-", m2)) => Op::Sub(m1, m2),
Some((m1, "*", m2)) => Op::Mul(m1, m2),
Some((m1, "/", m2)) => Op::Div(m1, m2),
_ => Op::Num(rest.parse().unwrap()),
};
(name.to_string(), op)
}).collect::<HashMap<_,_>>();
(name, op)
}).collect();
let mut values = HashMap::new();
let p1 = val(&monkies, &mut values, "root");
monkies.insert("humn".to_string(), Op::Num(-1337));
println!("{} = {}", val(&monkies, &mut values, "tfjf"), get_eq(&monkies, "vtsj").replace("-1337", "x"));
(p1,"glhf -> https://www.mathpapa.com/equation-solver/")
println!("{} = {}", val(&monkies, &mut values, "tfjf"), get_eq(&monkies, "vtsj"));
(val(&monkies, &mut values, "root"), "glhf -> https://www.mathpapa.com/equation-solver/")
}

0 comments on commit e25fe4d

Please sign in to comment.