Skip to content

Commit 260a177

Browse files
committed
Day 3 part 2
1 parent 71b0929 commit 260a177

File tree

3 files changed

+58
-0
lines changed

3 files changed

+58
-0
lines changed

src/adventofcode2024.gleam

+1
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ fn run(n: Int) -> Nil {
3434
io.println(case n {
3535
1 -> day1.part2(input) |> int.to_string
3636
2 -> day2.part2(input) |> int.to_string
37+
3 -> day3.part2(input) |> int.to_string
3738
_ -> "(not implemented)"
3839
})
3940
}

src/day3.gleam

+51
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,54 @@ pub fn part1(input: String) -> Int {
1818
|> list.reduce(fn(acc, v) { acc + v })
1919
|> result.unwrap(0)
2020
}
21+
22+
pub fn part2(input: String) -> Int {
23+
input |> parse_input |> process(True)
24+
}
25+
26+
fn process(input: List(Token), doing: Bool) -> Int {
27+
let #(head, tail) = list.split(input, 1)
28+
case list.first(head) {
29+
Ok(token) ->
30+
case token {
31+
Do -> process(tail, True)
32+
Dont -> process(tail, False)
33+
Mul(a, b) ->
34+
process(tail, doing)
35+
+ case doing {
36+
True -> a * b
37+
False -> 0
38+
}
39+
}
40+
Error(_) -> 0
41+
}
42+
}
43+
44+
type Token {
45+
Mul(a: Int, b: Int)
46+
Do
47+
Dont
48+
}
49+
50+
fn parse_input(input: String) -> List(Token) {
51+
let assert Ok(re) =
52+
regexp.from_string("mul\\((\\d+),(\\d+)\\)|do\\(\\)|don't\\(\\)")
53+
regexp.scan(re, input)
54+
|> list.map(fn(match) {
55+
case match.content {
56+
"do()" -> Do
57+
"don't()" -> Dont
58+
_ -> {
59+
// unwrap are safe due to regex, these are mul\(\d+,\d+\)
60+
let values =
61+
match.submatches
62+
|> list.map(fn(submatch) { option.unwrap(submatch, "") })
63+
|> list.filter_map(int.parse)
64+
Mul(
65+
values |> list.first |> result.unwrap(0),
66+
values |> list.drop(1) |> list.first |> result.unwrap(0),
67+
)
68+
}
69+
}
70+
})
71+
}

test/day3_test.gleam

+6
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,12 @@ pub fn main() {
99

1010
const example1 = "xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))\n"
1111

12+
const example2 = "xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5))\n"
13+
1214
pub fn part1_test() {
1315
day3.part1(example1) |> should.equal(161)
1416
}
17+
18+
pub fn part2_test() {
19+
day3.part2(example2) |> should.equal(48)
20+
}

0 commit comments

Comments
 (0)