From c4ffe154d886cb6c6e22ac6270a56ca315dd4010 Mon Sep 17 00:00:00 2001 From: sreedevk Date: Mon, 2 Dec 2024 03:39:21 +0000 Subject: [PATCH] day01: optimizations --- src/historian_hysteria.gleam | 26 ++++++++++++-------------- test/historian_hysteria_test.gleam | 1 - 2 files changed, 12 insertions(+), 15 deletions(-) diff --git a/src/historian_hysteria.gleam b/src/historian_hysteria.gleam index c753700..c2ae741 100644 --- a/src/historian_hysteria.gleam +++ b/src/historian_hysteria.gleam @@ -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) } diff --git a/test/historian_hysteria_test.gleam b/test/historian_hysteria_test.gleam index d3dc2f1..ce24da7 100644 --- a/test/historian_hysteria_test.gleam +++ b/test/historian_hysteria_test.gleam @@ -1,4 +1,3 @@ -import gleeunit import gleeunit/should import historian_hysteria as day01