-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday03.rs
66 lines (58 loc) · 2.01 KB
/
day03.rs
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
use std::fs;
use regex::Regex;
use crate::utils::toolbox::parse_usize;
pub fn day03(print: fn(usize)) {
print(part_a(fs::read_to_string("input/2024/day03/input.txt").unwrap()));
print(part_b(fs::read_to_string("input/2024/day03/input.txt").unwrap()));
}
fn part_a(input: String) -> usize {
let re = Regex::new(r"mul\((\d{1,3}),(\d{1,3})\)").unwrap();
input.lines()
.map(|line| {
re.captures_iter(line).map(|caps| {
let a = parse_usize(caps.get(1));
let b = parse_usize(caps.get(2));
a * b
}).sum::<usize>()
})
.sum()
}
fn part_b(input: String) -> usize {
let re = Regex::new(r"do\(\)|don't\(\)|mul\((\d{1,3}),(\d{1,3})\)").unwrap();
let mut enabled = true; // Start of program, not line! (lost minutes here)
input.lines()
.map(|line| {
re.captures_iter(line).map(|caps| {
let split = caps.get(0).unwrap().as_str();
if split.starts_with("don't") {
enabled = false;
0
} else if split.starts_with("do") {
enabled = true;
0
} else {
let a = parse_usize(caps.get(1));
let b = parse_usize(caps.get(2));
if enabled {
a * b
} else { 0 }
}
}).sum::<usize>()
})
.sum()
}
#[cfg(test)]
mod day03_tests {
use std::fs;
use crate::y2024::day03::{part_a, part_b};
#[test]
fn test_works() {
assert_eq!(161, part_a(fs::read_to_string("input/2024/day03/test.txt").unwrap()));
assert_eq!(48, part_b(fs::read_to_string("input/2024/day03/test2.txt").unwrap()));
}
#[test]
fn input_works() {
assert_eq!(185797128, part_a(fs::read_to_string("input/2024/day03/input.txt").unwrap()));
assert_eq!(89798695, part_b(fs::read_to_string("input/2024/day03/input.txt").unwrap()));
}
}