-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday_09.gleam
58 lines (52 loc) · 1.15 KB
/
day_09.gleam
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import gleam/bool
import gleam/int
import gleam/iterator
import gleam/list
import gleam/string
pub fn part_1(input: String) -> Int {
input
|> parse_input
|> list.map(fn(numbers) {
numbers
|> to_diff_sequences
|> list.filter_map(list.last)
|> int.sum
})
|> int.sum
}
pub fn part_2(input: String) -> Int {
input
|> parse_input
|> list.map(fn(numbers) {
numbers
|> to_diff_sequences
|> list.filter_map(list.first)
|> list.fold(0, fn(prev_number, number) { number - prev_number })
})
|> int.sum
}
fn parse_input(input: String) -> List(List(Int)) {
input
|> string.trim
|> string.split("\n")
|> list.map(fn(line) {
line
|> string.split(" ")
|> list.filter_map(int.parse)
})
}
fn to_diff_sequences(numbers: List(Int)) -> List(List(Int)) {
iterator.unfold(numbers, fn(prev_numbers) {
use <- bool.guard(
when: prev_numbers |> list.all(fn(n) { n == 0 }),
return: iterator.Done,
)
let next_numbers =
prev_numbers
|> list.window_by_2
|> list.map(fn(pair) { pair.1 - pair.0 })
iterator.Next(prev_numbers, next_numbers)
})
|> iterator.to_list
|> list.reverse
}