Day 1 Part 1

This commit is contained in:
April Eaton 2025-12-01 23:47:25 +01:00
parent a684fbe591
commit 32e35cd824
9 changed files with 4471 additions and 6 deletions

View file

@ -1,5 +1,78 @@
import gleam/int
import gleam/io
import gleam/list
import gleam/result
import gleam/string
import simplifile
pub type Rotation {
Left(Int)
Right(Int)
}
pub fn rotate(pos: Int, rot: Rotation) -> Int {
case rot {
Left(r) ->
case pos, r {
p, r if p < r -> 100 - { r - p }
p, r -> p - r
}
Right(r) -> { pos + r } % 100
}
}
pub fn rotate_step(hist: List(Int), rot: Rotation) -> List(Int) {
case hist {
[] -> [rotate(50, rot), 50]
[p, ..] -> [rotate(p, rot), ..hist]
}
}
pub fn count_zeros(l: List(Int)) -> Int {
list.filter(l, fn(x) { x == 0 }) |> list.length
}
pub fn line_to_rotation(l: String) -> Result(Rotation, Nil) {
let first_char = string.first(l)
let numeral =
string.drop_start(l, up_to: 1) |> int.parse |> result.map(fn(n) { n % 100 })
result.map(first_char, fn(c) {
case c {
"L" -> result.map(numeral, Left)
"R" -> result.map(numeral, Right)
_ -> Error(Nil)
}
})
|> result.flatten
}
pub fn read_line(file: String) -> Result(List(String), simplifile.FileError) {
simplifile.read(file) |> result.map(fn(c) { string.split(c, on: "\n") })
}
pub fn file_to_rotations(file: String) -> Result(List(Rotation), Nil) {
read_line(file)
|> result.map_error(fn(_) { Nil })
|> result.map(fn(ls) {
list.map(ls, line_to_rotation)
|> list.filter_map(fn(a) { a })
})
}
pub fn apply_rotations(rots: List(Rotation)) -> List(Int) {
list.fold(rots, [], rotate_step)
}
pub fn rotations_file_to_zeros(file: String) -> Result(Int, Nil) {
file_to_rotations(file)
|> result.map(apply_rotations)
|> result.map(count_zeros)
}
pub fn main() -> Nil {
io.println("Hello from day_1!")
let _ =
rotations_file_to_zeros("input.txt")
|> result.unwrap(-1)
|> int.to_string
|> io.println
}

2
day_1/src/good_test.txt Normal file
View file

@ -0,0 +1,2 @@
hello
world