summaryrefslogtreecommitdiffstats
path: root/day3/src/main.rs
blob: 86ba39bca2e0996d47a4fbb46ff5ad9a6da091cd (plain)
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
use aoc;
use std::io::{BufReader, Read};
use aoc::Day;
use regex::Regex;

struct Day3 {}

impl Day for Day3 {
    fn example_input(&self) -> &'static str {
        r#"
            xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))
        "#.trim()
    }

    fn example_input_part_2(&self) -> &'static str {
        r#"
            xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5))
        "#.trim()
    }

    fn example_result_part_1(&self) -> &'static str {
        "161"
    }

    fn example_result_part_2(&self) -> &'static str {
        "48"
    }

    fn part_1(&self, input: BufReader<Box<dyn Read>>) -> String {
        let code = self.read_lines(input).iter().map(|l| l.trim()).collect::<Vec<&str>>().join("");
        let re = Regex::new(r"mul\((?P<a>\d+),(?P<b>\d+)\)").unwrap();
        re
            .captures_iter(&code)
            .map(|c| {
                c.name("a").unwrap().as_str().parse::<u32>().unwrap() * c.name("b").unwrap().as_str().parse::<u32>().unwrap()
            })
            .sum::<u32>()
            .to_string()
    }

    fn part_2(&self, input: BufReader<Box<dyn Read>>) -> String {
        let code = self.read_lines(input).iter().map(|l| l.trim()).collect::<Vec<&str>>().join("");
        println!("{}", code);

        let mut mul = true;
        let re = Regex::new(r"mul\((?P<a>\d+),(?P<b>\d+)\)|(?P<enable>do)\(\)|(?P<disable>don't)\(\)").unwrap();
        re
            .captures_iter(&code)
            .map(|c| {

                if c.name("enable") != None {
                    mul = true;
                } else if c.name("disable") != None {
                    mul = false;
                } else if mul {
                    return c.name("a").unwrap().as_str().parse::<u32>().unwrap() * c.name("b").unwrap().as_str().parse::<u32>().unwrap();
                }

                0
            })
            .sum::<u32>()
            .to_string()
    }
}


fn main() {
    aoc::main(&Day3 {});
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_day3() {
        aoc::test_day(&Day3 {});
    }
}