This commit is contained in:
Hamcha 2024-12-03 22:14:33 +01:00
parent 1710799225
commit 68f61fb9e1
Signed by: hamcha
GPG key ID: 1669C533B8CF6D89
3 changed files with 121 additions and 0 deletions

7
sample/day2-sample.txt Normal file
View file

@ -0,0 +1,7 @@
7 6 4 2 1
1 2 7 8 9
9 7 6 2 1
1 3 2 4 5
8 6 4 4 1
1 3 6 7 9
35 30 29 28 26

51
src/day2_p1.gleam Normal file
View file

@ -0,0 +1,51 @@
import gleam/int
import gleam/io
import gleam/iterator
import gleam/list.{count, filter_map, map}
import gleam/string
import stdin.{stdin}
pub fn main() {
stdin()
|> parse
|> count(fn(x) { is_safe(x) })
|> io.debug
}
type Direction {
Increasing
Decreasing
}
fn is_safe(list: List(Int)) -> Bool {
// Evaluate direction, then call the actual checking function
case list {
[a, b, ..rest] if a > b -> is_safe_dir([a, b, ..rest], Decreasing)
[a, b, ..rest] if a < b -> is_safe_dir([a, b, ..rest], Increasing)
_ -> False
}
}
fn is_safe_dir(list: List(Int), dir: Direction) -> Bool {
case list {
[x, y] | [x, y, ..] if x <= y && dir == Decreasing -> False
[x, y] | [x, y, ..] if x >= y && dir == Increasing -> False
[x, y] | [x, y, ..] if x - y > 3 || y - x > 3 -> False
[_, ..rest] -> is_safe_dir(rest, dir)
_ -> True
}
}
fn parse(it: iterator.Iterator(String)) -> List(List(Int)) {
it
|> iterator.fold([[]], fn(acc, line) {
case string.trim(line) {
"" -> acc
str -> {
[str |> string.split(" ") |> filter_map(int.parse), ..acc]
}
}
})
|> list.filter(fn(l) { list.length(l) > 0 })
|> list.reverse
}

63
src/day2_p2.gleam Normal file
View file

@ -0,0 +1,63 @@
import gleam/int
import gleam/io
import gleam/iterator
import gleam/list.{any, count, filter_map, flatten, length, range, split}
import gleam/string
import stdin.{stdin}
pub fn main() {
stdin()
|> parse
|> count(fn(x) { is_safe_all_combo(x) })
|> io.debug
}
type Direction {
Increasing
Decreasing
}
fn is_safe_all_combo(list: List(Int)) -> Bool {
case is_safe(list) {
True -> True
False ->
range(0, length(list) - 1)
|> any(fn(index) {
let assert #(before, [_, ..after]) = list |> split(index)
flatten([before, after]) |> is_safe
})
}
}
fn is_safe(list: List(Int)) -> Bool {
// Evaluate direction, then call the actual checking function
case list {
[a, b, ..rest] if a > b -> is_safe_dir([a, b, ..rest], Decreasing)
[a, b, ..rest] if a < b -> is_safe_dir([a, b, ..rest], Increasing)
_ -> False
}
}
fn is_safe_dir(list: List(Int), dir: Direction) -> Bool {
case list {
[x, y] | [x, y, ..] if x <= y && dir == Decreasing -> False
[x, y] | [x, y, ..] if x >= y && dir == Increasing -> False
[x, y] | [x, y, ..] if x - y > 3 || y - x > 3 -> False
[_, ..rest] -> is_safe_dir(rest, dir)
_ -> True
}
}
fn parse(it: iterator.Iterator(String)) -> List(List(Int)) {
it
|> iterator.fold([[]], fn(acc, line) {
case string.trim(line) {
"" -> acc
str -> {
[str |> string.split(" ") |> filter_map(int.parse), ..acc]
}
}
})
|> list.filter(fn(l) { list.length(l) > 0 })
|> list.reverse
}