Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit b253387

Browse files
hms5232weihanglo
authored andcommitted
hms5232 2024 day3 part2
1 parent 1160f04 commit b253387

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

‎2024/03/hms5232/src/main.rs‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ fn main() {
55
let file_path = "input.txt"; // change this to the path of your file
66
let contents = std::fs::read_to_string(file_path).expect("File Read error");
77

8+
/* Part 1 */
9+
810
let re = Regex::new(r"mul\(\d{1,3},\d{1,3}\)").unwrap();
911
let matches: Vec<_> = re.find_iter(&contents).map(|m| {
1012
m.as_str().replace("mul(", "").replace(")", "")
@@ -16,4 +18,37 @@ fn main() {
1618
}).sum::<u32>();
1719

1820
println!("Part 1: {}", part1_answer);
21+
22+
/* Part 2 */
23+
24+
let re = Regex::new(r"mul\(\d{1,3},\d{1,3}\)|do\(\)|don't\(\)").unwrap();
25+
let matches: Vec<_> = re.find_iter(&contents).map(|m| m.as_str()).collect();
26+
let mut control_flag = true;
27+
let part2_answer: u32 = matches
28+
.iter()
29+
.map(|m| match *m {
30+
"do()" => {
31+
control_flag = true;
32+
return 0;
33+
}
34+
"don't()" => {
35+
control_flag = false;
36+
return 0;
37+
}
38+
_ => {
39+
if !control_flag {
40+
return 0;
41+
}
42+
let nums: Vec<u32> = m
43+
.replace("mul(", "")
44+
.replace(")", "")
45+
.split(",")
46+
.map(|n| n.parse().unwrap())
47+
.collect();
48+
nums[0] * nums[1]
49+
}
50+
})
51+
.sum();
52+
53+
println!("Part 2: {}", part2_answer);
1954
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /