Skip to content

Commit

Permalink
day01: optimizations
Browse files Browse the repository at this point in the history
  • Loading branch information
sreedevk committed Dec 2, 2024
1 parent 1df83bb commit c4ffe15
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 15 deletions.
26 changes: 12 additions & 14 deletions src/historian_hysteria.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -5,41 +5,39 @@ import gleam/result
import gleam/string

fn parse_line(line: String) -> List(Int) {
use line <- list.map(string.split(line, " "))
result.unwrap(int.parse(line), 0)
use a <- list.map(string.split(line, " "))
result.unwrap(int.parse(a), 0)
}

fn dist(scans: #(Int, Int)) {
int.absolute_value(pair.second(scans) - pair.first(scans))
}

fn freq_score_gen(ys: List(Int)) {
fn(x) { x * list.count(ys, fn(y) { y == x }) }
}

pub fn solve_a(input) -> Int {
input
|> string.trim()
|> string.split("\n")
|> list.map(parse_line)
|> list.transpose()
|> list.map(fn(x) { list.reverse(x) })
|> list.map(fn(x) { list.sort(x, int.compare) })
|> list.map(list.sort(_, int.compare))
|> list.reduce(fn(x, y) { list.map(list.zip(x, y), dist) })
|> result.unwrap([])
|> list.reduce(int.add)
|> result.map(list.reduce(_, int.add))
|> result.flatten()
|> result.unwrap(0)
}

fn similarity(x: Int, y: List(Int)) {
x * list.count(y, fn(z) { x == z })
}

pub fn solve_b(input) -> Int {
input
|> string.trim()
|> string.split("\n")
|> list.map(parse_line)
|> list.transpose()
|> list.map(fn(x) { list.reverse(x) })
|> list.reduce(fn(x, y) { list.map(x, fn(item) { similarity(item, y) }) })
|> result.unwrap([])
|> list.reduce(int.add)
|> list.reduce(fn(x, y) { list.map(x, freq_score_gen(y)) })
|> result.map(list.reduce(_, int.add))
|> result.flatten()
|> result.unwrap(0)
}
1 change: 0 additions & 1 deletion test/historian_hysteria_test.gleam
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import gleeunit
import gleeunit/should
import historian_hysteria as day01

Expand Down

0 comments on commit c4ffe15

Please sign in to comment.