Skip to main content

year2020/
day18.rs

1use utils::parser::{LeafResult, ParseError};
2use utils::prelude::*;
3
4/// Evaluating expressions under different precedence rules.
5#[derive(Clone, Debug)]
6pub struct Day18 {
7    part1: u64,
8    part2: u64,
9}
10
11impl Day18 {
12    pub fn new(input: &str, _: InputType) -> Result<Self, InputError> {
13        let (part1, part2) = Self::expression
14            .repeat_fold(
15                parser::eol(),
16                1,
17                Some((0u64, 0u64)),
18                |totals, (part1, part2)| {
19                    let (total1, total2) = totals?;
20                    Some((total1.checked_add(part1)?, total2.checked_add(part2)?))
21                },
22            )
23            .map_res(|totals| totals.ok_or("total too large"))
24            .parse_complete(input)?;
25        Ok(Self { part1, part2 })
26    }
27
28    #[must_use]
29    pub fn part1(&self) -> u64 {
30        self.part1
31    }
32
33    #[must_use]
34    pub fn part2(&self) -> u64 {
35        self.part2
36    }
37
38    fn expression(mut input: &[u8]) -> LeafResult<'_, (u64, u64)> {
39        let mut multiplication = false;
40        let mut part1 = 0u64;
41        let (mut current_sum, mut part2) = (0u64, 1u64);
42
43        loop {
44            let operand_input = input;
45            let ((operand1, operand2), remaining) = match input {
46                [digit @ b'0'..=b'9', rest @ ..] => {
47                    let operand = u64::from(digit - b'0');
48                    ((operand, operand), rest)
49                }
50                [b'(', rest @ ..] => match Self::expression(rest)? {
51                    (operands, [b')', rest @ ..]) => (operands, rest),
52                    (_, remaining) => return Err((ParseError::ExpectedByte(b')'), remaining)),
53                },
54                _ => return Err((ParseError::Expected("a digit or '('"), input)),
55            };
56
57            part1 = if multiplication {
58                part1.checked_mul(operand1)
59            } else {
60                part1.checked_add(operand1)
61            }
62            .ok_or((ParseError::Custom("result too large"), operand_input))?;
63
64            current_sum = current_sum
65                .checked_add(operand2)
66                .ok_or((ParseError::Custom("result too large"), operand_input))?;
67
68            match remaining {
69                [b' ', b'+', b' ', rest @ ..] => {
70                    multiplication = false;
71                    input = rest;
72                }
73                [b' ', b'*', b' ', rest @ ..] => {
74                    multiplication = true;
75                    part2 = part2
76                        .checked_mul(current_sum)
77                        .ok_or((ParseError::Custom("result too large"), remaining))?;
78                    current_sum = 0;
79                    input = rest;
80                }
81                [b')' | b'\n', ..] | [b'\r', b'\n', ..] | [] => {
82                    let product = part2
83                        .checked_mul(current_sum)
84                        .ok_or((ParseError::Custom("result too large"), remaining))?;
85                    return Ok(((part1, product), remaining));
86                }
87                _ => {
88                    return Err((
89                        ParseError::Custom("expected ' + ', ' * ', ')' or end of line"),
90                        remaining,
91                    ));
92                }
93            }
94        }
95    }
96}
97
98examples!(Day18 -> (u64, u64) [
99    {input: "1 + 2 * 3 + 4 * 5 + 6", part1: 71, part2: 231},
100    {input: "1 + (2 * 3) + (4 * (5 + 6))", part1: 51, part2: 51},
101    {input: "2 * 3 + (4 * 5)", part1: 26, part2: 46},
102    {input: "5 + (8 * 3 + 9 + 3 * 4 * 3)", part1: 437, part2: 1445},
103    {input: "5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))", part1: 12240, part2: 669060},
104    {input: "((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2", part1: 13632, part2: 23340},
105]);