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).
5use crate::util::parse::*;
6
7type Input = (u32, u32);
8
9pub fn parse(input: &str) -> Input {
10    let memory = input.as_bytes();
11    let mut index = 0;
12    let mut enabled = true;
13    let mut part_one = 0;
14    let mut part_two = 0;
15
16    while index < memory.len() {
17        // Skip junk characters
18        if memory[index] != b'm' && memory[index] != b'd' {
19            index += 1;
20            continue;
21        }
22
23        // Check possible prefixes
24        if memory[index..].starts_with(b"mul(") {
25            index += 4;
26        } else if memory[index..].starts_with(b"do()") {
27            index += 4;
28            enabled = true;
29            continue;
30        } else if memory[index..].starts_with(b"don't()") {
31            index += 7;
32            enabled = false;
33            continue;
34        } else {
35            index += 1;
36            continue;
37        }
38
39        // First number
40        let mut first = 0;
41
42        while memory[index].is_ascii_digit() {
43            first = 10 * first + memory[index].to_decimal() as u32;
44            index += 1;
45        }
46
47        // First delimiter
48        if memory[index] != b',' {
49            continue;
50        }
51        index += 1;
52
53        // Second number
54        let mut second = 0;
55
56        while memory[index].is_ascii_digit() {
57            second = 10 * second + memory[index].to_decimal() as u32;
58            index += 1;
59        }
60
61        // Second delimiter
62        if memory[index] != b')' {
63            continue;
64        }
65        index += 1;
66
67        // Multiply
68        let product = first * second;
69        part_one += product;
70        part_two += if enabled { product } else { 0 };
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}