Skip to content

Commit 1f24938

Browse files
committed
Add day 18
1 parent b1b0827 commit 1f24938

File tree

1 file changed

+11
-26
lines changed

1 file changed

+11
-26
lines changed

2020/18/18.rs

Lines changed: 11 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,35 @@
11
use std::{collections::HashMap, io::stdin};
22

3-
use itertools::Itertools;
4-
53
fn eval(line: &str, plus_precedence: i32) -> i64 {
64
let mut nums = Vec::new();
75
let mut operators = Vec::new();
8-
let precedence = HashMap::from([('(', 10), ('+', plus_precedence), ('*', 1)]);
9-
// eprintln!("line = {:?}", line);
6+
let precedence = HashMap::from([('(', 0), (')', 0), ('+', plus_precedence), ('*', 1)]);
7+
108
for c in line.chars().chain(")".chars()) {
11-
// eprintln!("c = {:?}, nums = {:?}, ops = {:?}", c, nums, operators);
129
match c {
1310
'0'..='9' => nums.push(c.to_digit(10).unwrap() as i64),
14-
'(' => operators.push(c),
15-
')' => {
16-
while !operators.is_empty() {
11+
'(' | '+' | '*' | ')' => {
12+
while !operators.is_empty() && c != '(' {
1713
let op = operators.pop().unwrap();
18-
if op == '(' {
14+
if op == '(' && c == ')' { break }
15+
if precedence.get(&op).unwrap() < precedence.get(&c).unwrap() {
16+
operators.push(op);
1917
break;
2018
}
2119
let func = if op == '*' { |(a, b)| a * b } else { |(a, b)| a + b };
2220
let value = nums.pop().zip(nums.pop()).map(func).unwrap();
2321
nums.push(value);
2422
}
25-
}
26-
'+' | '*' => {
27-
while !operators.is_empty() {
28-
// eprintln!("\tc = {:?}, nums = {:?}, ops = {:?}", c, nums, operators);
29-
let op = operators.last().unwrap();
30-
if *op == '(' || precedence.get(op).unwrap() < precedence.get(&c).unwrap() {
31-
break;
32-
}
33-
let func = if *op == '*' { |(a, b)| a * b } else { |(a, b)| a + b };
34-
let value = nums.pop().zip(nums.pop()).map(func).unwrap();
35-
nums.push(value);
36-
operators.pop();
37-
}
38-
operators.push(c);
23+
if c != ')' { operators.push(c); }
3924
},
40-
_ => (),
25+
_ => continue,
4126
}
4227
}
4328
*nums.get(0).unwrap()
4429
}
4530

4631
fn main() {
47-
let lines = stdin() .lines().filter_map(Result::ok).collect_vec();
32+
let lines: Vec<String> = stdin() .lines().filter_map(Result::ok).collect();
4833
println!("{:?}", lines.iter().map(|l| eval(&l, 1)).sum::<i64>());
4934
println!("{:?}", lines.iter().map(|l| eval(&l, 2)).sum::<i64>());
50-
}
35+
}

0 commit comments

Comments
 (0)