summaryrefslogtreecommitdiff
path: root/2024_rust/src/day3.rs
blob: cdcd62a47725f486bb690f7114e36933b310aad3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
use regex::Regex;

pub fn p1(input: &str) -> String {
    let re = Regex::new(r"mul\(([0-9]{1,3}),([0-9]{1,3})\)").unwrap();

    let mut result: u32 = 0;
    for (_, [x, y]) in re.captures_iter(input).map(|cs| cs.extract()) {
        result += x.parse::<u32>().unwrap() * y.parse::<u32>().unwrap();
    }

    result.to_string()
}

pub fn p2(input: &str) -> String {
    let re = Regex::new(r"do\(\)|don't\(\)|mul\(([0-9]{1,3}),([0-9]{1,3})\)").unwrap();

    let mut doing = true;
    let mut result: u32 = 0;
    for cs in re.captures_iter(input) {
        let mut it = cs.iter().flatten().map(|m| m.as_str());
        match it.next().unwrap() {
            "do()" => doing = true,
            "don't()" => doing = false,
            mul if doing && mul.starts_with("mul") => {
                let mut next = || it.next().unwrap().parse::<u32>().unwrap();
                result += next() * next();
            }
            _ => (),
        }
    }

    result.to_string()
}