summaryrefslogtreecommitdiff
path: root/2024/3/src/main.rs
blob: 0775483c3fe6b0e6134483de93d7b131c5a2e25f (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
34
35
36
37
38
39
40
41
use regex::Regex;

const INPUT_FILE: &str = "input";

fn p1(input: &str) {
    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();
    }

    println!("Result: {}", result);
}

fn p2(input: &str) {
    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();
            }
            _ => (),
        }
    }

    println!("Result: {}", result);
}

fn main() {
    let input = std::fs::read_to_string(INPUT_FILE).unwrap();
    p1(&input);
    p2(&input);
}