--- Day 18: Operation Order ---

As you look out the window and notice a heavily-forested continent slowly appear over the horizon, you are interrupted by the child sitting next to you. They're curious if you could help them with their math homework.

Unfortunately, it seems like this "math" follows different rules than you remember.

The homework (your puzzle input) consists of a series of expressions that consist of addition (+), multiplication (*), and parentheses ((...)). Just like normal math, parentheses indicate that the expression inside must be evaluated before it can be used by the surrounding expression. Addition still finds the sum of the numbers on both sides of the operator, and multiplication still finds the product.

However, the rules of operator precedence have changed. Rather than evaluating multiplication before addition, the operators have the same precedence, and are evaluated left-to-right regardless of the order in which they appear.

For example, the steps to evaluate the expression 1 + 2 * 3 + 4 * 5 + 6 are as follows:

1 + 2 * 3 + 4 * 5 + 6
  3   * 3 + 4 * 5 + 6
      9   + 4 * 5 + 6
         13   * 5 + 6
             65   + 6
                 71

Parentheses can override this order; for example, here is what happens if parentheses are added to form 1 + (2 * 3) + (4 * (5 + 6)):

1 + (2 * 3) + (4 * (5 + 6))
1 +    6    + (4 * (5 + 6))
     7      + (4 * (5 + 6))
     7      + (4 *   11   )
     7      +     44
            51

Here are a few more examples:

  • 2 * 3 + (4 * 5) becomes 26.
  • 5 + (8 * 3 + 9 + 3 * 4 * 3) becomes 437.
  • 5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4)) becomes 12240.
  • ((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2 becomes 13632.

Before you can help with the homework, you need to understand it yourself. Evaluate the expression on each line of the homework; what is the sum of the resulting values?

Rust Solution

use rustgym_util::*;
use std::fmt::Write;
use std::io::*;
use std::iter::Peekable;
use std::slice::Iter;

pub fn solve(reader: &mut dyn BufRead, writer: &mut dyn Write) {
    let it = reader.lines().map(|l| l.unwrap());
    let mut exprs: Vec<Vec<Tok>> = vec![];
    for line in it {
        let tokens = parse_expr(&line);
        exprs.push(tokens);
    }
    let res1: i64 = exprs.iter().map(|e| eval_expr1(e)).sum();
    let res2: i64 = exprs.iter().map(|e| eval_expr2(e)).sum();
    writeln!(writer, "{}", res1).unwrap();
    writeln!(writer, "{}", res2).unwrap();
}

#[derive(Debug)]
enum Tok {
    Num(i64),
    Op(char),
}

fn parse_expr(s: &str) -> Vec<Tok> {
    let mut tokens: Vec<Tok> = vec![];
    for c in s.chars() {
        match c {
            '(' | ')' | '+' | '*' => tokens.push(Tok::Op(c)),
            '0'..='9' => tokens.push(Tok::Num((c as u8 - b'0') as i64)),
            _ => {}
        }
    }
    tokens
}

fn eval_expr1(e: &[Tok]) -> i64 {
    let mut it = e.iter().peekable();
    expr1(&mut it)
}

fn eval_expr2(e: &[Tok]) -> i64 {
    let mut it = e.iter().peekable();
    expr2(&mut it)
}

fn expr1(it: &mut Peekable<Iter<Tok>>) -> i64 {
    let mut res = term1(it);
    while let Some(Tok::Op(c)) = it.peek() {
        match c {
            '+' => {
                it.next().unwrap();
                res += term1(it);
            }
            '*' => {
                it.next().unwrap();
                res *= term1(it);
            }
            ')' => {
                break;
            }
            _ => {
                panic!();
            }
        }
    }
    res
}

fn expr2(it: &mut Peekable<Iter<Tok>>) -> i64 {
    let mut res = fact2(it);
    while let Some(Tok::Op(c)) = it.peek() {
        match c {
            '*' => {
                it.next().unwrap();
                res *= fact2(it);
            }
            ')' | '+' => {
                break;
            }
            _ => {
                panic!();
            }
        }
    }
    res
}

fn fact2(it: &mut Peekable<Iter<Tok>>) -> i64 {
    let mut res = term2(it);
    while let Some(Tok::Op(c)) = it.peek() {
        match c {
            '+' => {
                it.next().unwrap();
                res += term2(it);
            }
            ')' | '*' => {
                break;
            }
            _ => {
                panic!();
            }
        }
    }
    res
}

fn term1(it: &mut Peekable<Iter<Tok>>) -> i64 {
    match it.next() {
        Some(&Tok::Num(x)) => x,
        Some(Tok::Op('(')) => {
            let res = expr1(it);
            it.next().unwrap();
            res
        }
        _ => panic!(),
    }
}

fn term2(it: &mut Peekable<Iter<Tok>>) -> i64 {
    match it.next() {
        Some(&Tok::Num(x)) => x,
        Some(Tok::Op('(')) => {
            let res = expr2(it);
            it.next().unwrap();
            res
        }
        _ => panic!(),
    }
}

advent_of_code!(test, "input.txt", "output.txt");

Having problems with this solution? Click here to submit an issue on github.