aboutsummaryrefslogtreecommitdiff
path: root/codingquest2024/src/day4/solution.gleam
diff options
context:
space:
mode:
authorJ.J <thechairman@thechairman.info>2024-05-30 21:49:58 -0400
committerJ.J <thechairman@thechairman.info>2024-05-30 21:49:58 -0400
commit231c2b688d1e6cf0846d46e883da30e042a9c6cf (patch)
tree98a6d3a461fe190b38b2cf33a708a1d01703fa70 /codingquest2024/src/day4/solution.gleam
parentfe088aa5778dcdbaab4dd8d4a7395a91c444b45c (diff)
parenta2c2b728ec6051323ed937f54816089cd2ae9d20 (diff)
downloadgleam_aoc-231c2b688d1e6cf0846d46e883da30e042a9c6cf.tar.gz
gleam_aoc-231c2b688d1e6cf0846d46e883da30e042a9c6cf.zip
Merge branch 'main' of https://github.com/hunkyjimpjorps/AdventOfCode
Diffstat (limited to 'codingquest2024/src/day4/solution.gleam')
-rw-r--r--codingquest2024/src/day4/solution.gleam49
1 files changed, 49 insertions, 0 deletions
diff --git a/codingquest2024/src/day4/solution.gleam b/codingquest2024/src/day4/solution.gleam
new file mode 100644
index 0000000..a03b2be
--- /dev/null
+++ b/codingquest2024/src/day4/solution.gleam
@@ -0,0 +1,49 @@
+import gleam/float
+import gleam/io
+import gleam/list
+import gleam/regex
+import gleam/result
+import gleam/string
+import simplifile
+
+pub type Star {
+ Star(name: String, x: Float, y: Float, z: Float)
+}
+
+pub fn main() {
+ let assert Ok(data) = simplifile.read(from: "./src/day4/data.txt")
+
+ let assert [_, ..stars] = string.split(data, "\n")
+
+ stars
+ |> list.map(parse_star_record)
+ |> list.combination_pairs()
+ |> list.map(star_distance)
+ |> list.reduce(float.min)
+ |> io.debug
+}
+
+fn parse_star_record(str: String) -> Star {
+ let assert Ok(re) = regex.from_string("\\s{2,}")
+
+ let assert [name, ..coords] = regex.split(with: re, content: str)
+ let assert [_, x, y, z] =
+ coords
+ |> list.map(float.parse)
+ |> result.values
+
+ Star(name, x, y, z)
+}
+
+fn star_distance(stars: #(Star, Star)) -> Float {
+ let #(star1, star2) = stars
+ let assert Ok(dist) =
+ float.square_root(
+ sq(star1.x -. star2.x) +. sq(star1.y -. star2.y) +. sq(star1.z -. star2.z),
+ )
+ dist
+}
+
+fn sq(x: Float) -> Float {
+ x *. x
+}