Skip to content

Commit 06187f1

Browse files
committed
Day 4 part 2
1 parent faeb73b commit 06187f1

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed

src/adventofcode2024.gleam

+1
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ fn run(n: Int) -> Nil {
3737
1 -> day1.part2(input) |> int.to_string
3838
2 -> day2.part2(input) |> int.to_string
3939
3 -> day3.part2(input) |> int.to_string
40+
4 -> day4.part2(input) |> int.to_string
4041
_ -> "(not implemented)"
4142
})
4243
}

src/day4.gleam

+31
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,14 @@ pub fn part1(input: String) -> Int {
1313
|> int.sum
1414
}
1515

16+
pub fn part2(input: String) -> Int {
17+
let grid = parse.grid(input)
18+
19+
grid
20+
|> dict.to_list
21+
|> list.count(fn(kv) { is_cross_mas(grid, kv.0) })
22+
}
23+
1624
type Dir {
1725
N
1826
NE
@@ -61,3 +69,26 @@ fn next_cell(from: #(Int, Int), dir: Dir) -> #(Int, Int) {
6169
NW -> #(from.0 - 1, from.1 - 1)
6270
}
6371
}
72+
73+
fn is_cross_mas(grid: parse.Grid, at: #(Int, Int)) -> Bool {
74+
case get_at(grid, at) {
75+
"A" -> {
76+
let ne = get_at(grid, next_cell(at, NE))
77+
let se = get_at(grid, next_cell(at, SE))
78+
let sw = get_at(grid, next_cell(at, SW))
79+
let nw = get_at(grid, next_cell(at, NW))
80+
let diag1 = sw <> ne
81+
let diag2 = nw <> se
82+
83+
{ diag1 == "MS" || diag1 == "SM" } && { diag2 == "MS" || diag2 == "SM" }
84+
}
85+
_ -> False
86+
}
87+
}
88+
89+
fn get_at(grid: parse.Grid, at: #(Int, Int)) -> String {
90+
case dict.get(grid, at) {
91+
Ok(value) -> value
92+
Error(_) -> ""
93+
}
94+
}

test/day4_test.gleam

+4
Original file line numberDiff line numberDiff line change
@@ -22,3 +22,7 @@ MXMXAXMASX
2222
pub fn part1_test() {
2323
day4.part1(example1) |> should.equal(18)
2424
}
25+
26+
pub fn part2_test() {
27+
day4.part2(example1) |> should.equal(9)
28+
}

0 commit comments

Comments
 (0)