aoc/year2024/
day03.rs

1//! # Mull It Over
2//!
3//! Solves both parts simultaneously using a custom parser instead of
4//! [regex](https://en.wikipedia.org/wiki/Regular_expression).
5type Input = (u32, u32);
6
7pub fn parse(input: &str) -> Input {
8    let memory = input.as_bytes();
9    let mut index = 0;
10    let mut enabled = true;
11    let mut part_one = 0;
12    let mut part_two = 0;
13
14    while index < memory.len() {
15        // Skip junk characters
16        if memory[index] != b'm' && memory[index] != b'd' {
17            index += 1;
18            continue;
19        }
20
21        // Check possible prefixes
22        if memory[index..].starts_with(b"mul(") {
23            index += 4;
24        } else if memory[index..].starts_with(b"do()") {
25            index += 4;
26            enabled = true;
27            continue;
28        } else if memory[index..].starts_with(b"don't()") {
29            index += 7;
30            enabled = false;
31            continue;
32        } else {
33            index += 1;
34            continue;
35        }
36
37        // First number
38        let mut first = 0;
39
40        while memory[index].is_ascii_digit() {
41            first = 10 * first + (memory[index] - b'0') as u32;
42            index += 1;
43        }
44
45        // First delimiter
46        if memory[index] != b',' {
47            continue;
48        }
49        index += 1;
50
51        // Second number
52        let mut second = 0;
53
54        while memory[index].is_ascii_digit() {
55            second = 10 * second + (memory[index] - b'0') as u32;
56            index += 1;
57        }
58
59        // Second delimiter
60        if memory[index] != b')' {
61            continue;
62        }
63        index += 1;
64
65        // Multiply
66        let product = first * second;
67        part_one += product;
68        if enabled {
69            part_two += product;
70        }
71    }
72
73    (part_one, part_two)
74}
75
76pub fn part1(input: &Input) -> u32 {
77    input.0
78}
79
80pub fn part2(input: &Input) -> u32 {
81    input.1
82}