Skip to content

Commit

Permalink
Improve the code with helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
Janiczek committed Dec 1, 2024
1 parent 737835b commit a6d150c
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
12 changes: 8 additions & 4 deletions src/aoc_2024/day_1.gleam
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import extra
import gleam/dict
import gleam/int
import gleam/io
import gleam/list
import gleam/result
import gleam/string

pub type Input =
Expand Down Expand Up @@ -28,12 +30,14 @@ pub fn pt_1(input: Input) {
let sorted_xs = xs |> list.sort(by: int.compare)
let sorted_ys = ys |> list.sort(by: int.compare)
list.map2(sorted_xs, sorted_ys, with: fn(x, y) { int.absolute_value(x - y) })
|> list.fold(from: 0, with: int.add)
|> int.sum
}

pub fn pt_2(input: Input) {
let #(xs, ys) = input
let freqs = extra.frequencies(ys)

xs
|> list.map(fn(x) { x * list.count(ys, where: fn(y) { x == y }) })
|> list.fold(from: 0, with: int.add)
|> list.map(fn(x) { x * { dict.get(freqs, x) |> result.unwrap(0) } })
|> int.sum
}
16 changes: 16 additions & 0 deletions src/extra.gleam
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import gleam/dict.{type Dict}
import gleam/list
import gleam/result

pub fn frequencies(xs: List(a)) -> Dict(a, Int) {
xs
|> list.fold(from: dict.new(), with: fn(counter, x) {
let old: Int =
counter
|> dict.get(x)
|> result.unwrap(0)

counter
|> dict.insert(x, old + 1)
})
}

0 comments on commit a6d150c

Please sign in to comment.