From bc9ad3f333d4f6f72bb71c8c7dc9cf53ea0618f7 Mon Sep 17 00:00:00 2001 From: Pedro Correa Date: Mon, 5 Jan 2026 15:11:16 -0300 Subject: [PATCH] :sparkles: (Gleam) aoc day 9 --- src/day_09.gleam | 53 ++++++++++++++++++++++++++++++++++++++++++ test/day_09_test.gleam | 47 +++++++++++++++++++++++++++++++++++++ 2 files changed, 100 insertions(+) create mode 100644 src/day_09.gleam create mode 100644 test/day_09_test.gleam diff --git a/src/day_09.gleam b/src/day_09.gleam new file mode 100644 index 0000000..8f22e48 --- /dev/null +++ b/src/day_09.gleam @@ -0,0 +1,53 @@ +import gleam/bool +import gleam/int +import gleam/list +import gleam/pair +import gleam/string + +type Coordinates = + List(#(Int, Int)) + +pub fn format_input(input: String) -> Coordinates { + use line <- list.filter_map(input |> string.split("\n")) + + use <- bool.guard(when: line == "", return: Error("")) + + let assert [x, y] = line |> string.split(",") + let assert Ok(new_x) = int.parse(x) + let assert Ok(new_y) = int.parse(y) + + Ok(#(new_x, new_y)) +} + +fn calculate_axis_distance(first: #(Int, Int), second: #(Int, Int)) { + fn(abs_function: fn(#(Int, Int)) -> Int) -> Int { + let pf = abs_function(first) + let ps = abs_function(second) + + case pf > ps { + True -> pf - ps + 1 + _ -> ps - pf + 1 + } + } +} + +fn calculate_distance(first: #(Int, Int), second: #(Int, Int)) -> Int { + let calculate_with_axis = calculate_axis_distance(first, second) + + calculate_with_axis(pair.first) * calculate_with_axis(pair.second) +} + +pub fn calculate_area(coordinates: Coordinates) -> Int { + coordinates + |> list.combination_pairs + |> list.fold(0, fn(acc, values) { + let #(first, second) = values + + let value = calculate_distance(first, second) + + case value > acc { + True -> value + _ -> acc + } + }) +} diff --git a/test/day_09_test.gleam b/test/day_09_test.gleam new file mode 100644 index 0000000..f6f934e --- /dev/null +++ b/test/day_09_test.gleam @@ -0,0 +1,47 @@ +import day_09 +import simplifile + +pub fn read_file_test() { + assert "7,1 +11,1 +11,7 +9,7 +9,5 +2,5 +2,3 +7,3" + |> day_09.format_input + == [ + #(7, 1), + #(11, 1), + #(11, 7), + #(9, 7), + #(9, 5), + #(2, 5), + #(2, 3), + #(7, 3), + ] +} + +pub fn calculate_area_test() { + assert "7,1 +11,1 +11,7 +9,7 +9,5 +2,5 +2,3 +7,3" + |> day_09.format_input + |> day_09.calculate_area + == 50 +} + +pub fn calculate_distances_for_real_test() { + let assert Ok(file) = simplifile.read("input/day_09") + + assert file + |> day_09.format_input + |> day_09.calculate_area + == 4_758_121_828 +} -- 2.51.2