summaryrefslogtreecommitdiff
path: root/2024/3/src/main.rs
blob: cadc1fe438f38e29dd0b4dcddfab3248aabbd68e (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
42
43
44
45
46
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(|m| m.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 m in re.captures_iter(input) {
        let mut it = m.iter();
        match it.next().unwrap().map(|m| m.as_str()) {
            Some("do()") => doing = true,
            Some("don't()") => doing = false,
            Some(mul) if doing && mul.starts_with("mul") => {
                if let [x, y] = it
                    .flatten()
                    .map(|m| m.as_str().parse::<u32>().unwrap())
                    .collect::<Vec<u32>>()[..]
                {
                    result += x * y;
                }
            }
            _ => (),
        }
    }

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

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