Skip to main content

aoc/year2020/
day18.rs

1//! # Operation Order
2//!
3//! For part one the operator precedence is the same so we proceed from left to right for
4//! each expression. Parentheses are handled via recursion, so we return either when encountering
5//! the end of the string or a `)` character.
6//!
7//! For part two whenever we encounter the lower priority `*` operator then we *implicitly* insert
8//! parentheses around the remaining expression. For example:
9//!
10//! * 1 * 2 * 3 * 4 => 1 * (2 * (3 * (4)))
11//! * 1 + 2 * 3 + 4 => 1 + 2 * (3 + 4)
12//! * 1 + (2 * 3 * 4) + 5 => 1 + (2 * (3 * (4))) + 5
13use std::str::Bytes;
14
15use crate::util::parse::*;
16
17pub fn parse(input: &str) -> Vec<&str> {
18    input.lines().collect()
19}
20
21pub fn part1(input: &[&str]) -> u64 {
22    fn helper(bytes: &mut Bytes<'_>) -> u64 {
23        let mut total = value(bytes, helper);
24
25        while let Some(operation) = next(bytes) {
26            let value = value(bytes, helper);
27            if operation == b'+' {
28                total += value;
29            } else {
30                total *= value;
31            }
32        }
33
34        total
35    }
36
37    input.iter().map(|line| helper(&mut line.bytes())).sum()
38}
39
40pub fn part2(input: &[&str]) -> u64 {
41    fn helper(bytes: &mut Bytes<'_>) -> u64 {
42        let mut total = value(bytes, helper);
43
44        while let Some(operation) = next(bytes) {
45            if operation == b'+' {
46                total += value(bytes, helper);
47            } else {
48                // Implicitly insert '(' and ')' around the remaining sub-expression so when it
49                // finishes we break too.
50                total *= helper(bytes);
51                break;
52            }
53        }
54
55        total
56    }
57
58    input.iter().map(|line| helper(&mut line.bytes())).sum()
59}
60
61/// Convenience wrapper around [`Bytes`] iterator. Encountering a `)` is also considered end of
62/// sequence. The expressions are consistently formatted so encountering a space just means
63/// skip and return the next character that will always be present.
64fn next(bytes: &mut Bytes<'_>) -> Option<u8> {
65    match bytes.next() {
66        None | Some(b')') => None,
67        Some(b' ') => bytes.next(),
68        other => other,
69    }
70}
71
72/// Convenience wrapper to return the value of either the next raw digit literal or a
73/// sub-expression nested in parentheses.
74fn value(bytes: &mut Bytes<'_>, helper: fn(&mut Bytes<'_>) -> u64) -> u64 {
75    match next(bytes).unwrap() {
76        b'(' => helper(bytes),
77        b => b.to_decimal(),
78    }
79}