Skip to content

Commit 63b9013

Browse files
committed
Refactoring
1 parent 64d63f2 commit 63b9013

File tree

1 file changed

+30
-29
lines changed

1 file changed

+30
-29
lines changed

src/aoc/year2024/day18.gleam

+30-29
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,7 @@ type Node =
1919
#(Int, Coord)
2020

2121
fn order(a: Node, b: Node) -> Order {
22-
let #(a_score, _) = a
23-
let #(b_score, _) = b
24-
int.compare(a_score, b_score)
22+
int.compare(a.0, b.0)
2523
}
2624

2725
fn make_grid(size: Int, bytes: List(Coord)) -> Grid {
@@ -54,30 +52,31 @@ fn neighbors(grid: Grid, coord: Coord) -> List(Coord) {
5452
|> list.filter(fn(c) { dict.get(grid, c) == Ok(".") })
5553
}
5654

57-
fn steps(grid: Grid, q: Queue(Node), goal: Coord, seen: Set(Coord)) -> Int {
58-
case pq.pop(q) {
59-
Error(_) -> -1
60-
Ok(#(#(score, coord), _)) if coord == goal -> score
61-
Ok(#(node, q)) -> {
62-
let #(score, coord) = node
63-
case set.contains(seen, coord) {
64-
True -> steps(grid, q, goal, seen)
65-
False -> {
66-
let seen = set.insert(seen, coord)
67-
let q =
68-
grid
69-
|> neighbors(coord)
70-
|> list.filter_map(fn(c) {
71-
case set.contains(seen, c) {
72-
True -> Error(Nil)
73-
False -> Ok(#(score + 1, c))
74-
}
75-
})
76-
|> list.fold(q, pq.push)
77-
78-
steps(grid, q, goal, seen)
79-
}
80-
}
55+
fn steps(
56+
grid: Grid,
57+
q: Queue(Node),
58+
goal: Coord,
59+
seen: Set(Coord),
60+
) -> Result(Int, Nil) {
61+
use #(#(score, coord), q) <- result.try(pq.pop(q))
62+
63+
case coord == goal, set.contains(seen, coord) {
64+
True, _ -> Ok(score)
65+
False, True -> steps(grid, q, goal, seen)
66+
False, False -> {
67+
let seen = set.insert(seen, coord)
68+
let q =
69+
grid
70+
|> neighbors(coord)
71+
|> list.filter_map(fn(c) {
72+
case set.contains(seen, c) {
73+
True -> Error(Nil)
74+
False -> Ok(#(score + 1, c))
75+
}
76+
})
77+
|> list.fold(q, pq.push)
78+
79+
steps(grid, q, goal, seen)
8180
}
8281
}
8382
}
@@ -98,7 +97,9 @@ pub fn part1(input: String, size: Int, n: Int) -> Int {
9897
let grid = make_grid(size, bytes)
9998
let q = pq.from_list([#(0, #(0, 0))], order)
10099

101-
steps(grid, q, #(size, size), set.new())
100+
grid
101+
|> steps(q, #(size, size), set.new())
102+
|> result.unwrap(-1)
102103
}
103104

104105
pub fn part2(input: String, size: Int) -> String {
@@ -112,7 +113,7 @@ pub fn part2(input: String, size: Int) -> String {
112113
|> yielder.find_map(fn(p) {
113114
let #(#(x, y), grid) = p
114115
case steps(grid, q, goal, set.new()) {
115-
-1 -> Ok(int.to_string(x) <> "," <> int.to_string(y))
116+
Error(Nil) -> Ok(int.to_string(x) <> "," <> int.to_string(y))
116117
_ -> Error(Nil)
117118
}
118119
})

0 commit comments

Comments
 (0)