From ccc0a88c0e8a1ad25e5543ab48b33bc18744708b Mon Sep 17 00:00:00 2001 From: Robert Attard Date: Mon, 2 Dec 2024 17:02:28 +0100 Subject: [PATCH] 2024 day 2 --- gleam.toml | 1 + src/aoc_2024/day_2.gleam | 42 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 src/aoc_2024/day_2.gleam diff --git a/gleam.toml b/gleam.toml index f157aa6..03b32b7 100644 --- a/gleam.toml +++ b/gleam.toml @@ -57,3 +57,4 @@ gleeunit = ">= 1.2.0 and < 2.0.0" [gladvent.2024] 1 = { pt_1 = 1579939, pt_2 = 20351745 } +2 = { pt_1 = 282, pt_2 = 349 } diff --git a/src/aoc_2024/day_2.gleam b/src/aoc_2024/day_2.gleam new file mode 100644 index 0000000..0c02e50 --- /dev/null +++ b/src/aoc_2024/day_2.gleam @@ -0,0 +1,42 @@ +import gleam/int +import gleam/list +import gleam/result +import gleam/string + +pub fn parse(input: String) -> List(List(Int)) { + use line <- list.map(string.split(input, "\n")) + use item <- list.map(string.split(line, " ")) + let assert Ok(i) = int.parse(item) + i +} + +type Direction { + Increasing + Decreasing + Start +} + +fn is_safe(line: List(Int)) -> Bool { + { + use safety, #(left, right) <- list.try_fold(list.window_by_2(line), Start) + let diff = right - left + case safety { + Start | Increasing if diff >= 1 && diff <= 3 -> Ok(Increasing) + Start | Decreasing if diff <= -1 && diff >= -3 -> Ok(Decreasing) + _ -> Error(Nil) + } + } + |> result.is_ok +} + +pub fn pt_1(input: List(List(Int))) { + input |> list.filter(is_safe) |> list.length +} + +pub fn pt_2(input: List(List(Int))) { + input + |> list.filter(fn(line) { + list.any(list.combinations(line, list.length(line) - 1), is_safe) + }) + |> list.length +}