Skip to content

Commit a6d150c

Browse files
committed
Improve the code with helpers
1 parent 737835b commit a6d150c

File tree

2 files changed

+24
-4
lines changed

2 files changed

+24
-4
lines changed

src/aoc_2024/day_1.gleam

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1+
import extra
2+
import gleam/dict
13
import gleam/int
2-
import gleam/io
34
import gleam/list
5+
import gleam/result
46
import gleam/string
57

68
pub type Input =
@@ -28,12 +30,14 @@ pub fn pt_1(input: Input) {
2830
let sorted_xs = xs |> list.sort(by: int.compare)
2931
let sorted_ys = ys |> list.sort(by: int.compare)
3032
list.map2(sorted_xs, sorted_ys, with: fn(x, y) { int.absolute_value(x - y) })
31-
|> list.fold(from: 0, with: int.add)
33+
|> int.sum
3234
}
3335

3436
pub fn pt_2(input: Input) {
3537
let #(xs, ys) = input
38+
let freqs = extra.frequencies(ys)
39+
3640
xs
37-
|> list.map(fn(x) { x * list.count(ys, where: fn(y) { x == y }) })
38-
|> list.fold(from: 0, with: int.add)
41+
|> list.map(fn(x) { x * { dict.get(freqs, x) |> result.unwrap(0) } })
42+
|> int.sum
3943
}

src/extra.gleam

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import gleam/dict.{type Dict}
2+
import gleam/list
3+
import gleam/result
4+
5+
pub fn frequencies(xs: List(a)) -> Dict(a, Int) {
6+
xs
7+
|> list.fold(from: dict.new(), with: fn(counter, x) {
8+
let old: Int =
9+
counter
10+
|> dict.get(x)
11+
|> result.unwrap(0)
12+
13+
counter
14+
|> dict.insert(x, old + 1)
15+
})
16+
}

0 commit comments

Comments
 (0)