-
Notifications
You must be signed in to change notification settings - Fork 0
/
day_1.gleam
114 lines (98 loc) · 2.32 KB
/
day_1.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import gleam/dict
import gleam/int
import gleam/list
import gleam/option
import gleam/result
import gleam/string
// Expects both lists to be sorted
fn solve_part_one(left: List(Int), right: List(Int), distance_accumulator: Int) {
case left {
[first, ..rest] -> {
let right_remaining = list.rest(right) |> result.unwrap([])
let right_value = list.first(right) |> result.unwrap(0)
let distance =
first
|> int.subtract(right_value)
|> int.absolute_value
solve_part_one(rest, right_remaining, { distance_accumulator + distance })
}
_ -> distance_accumulator
}
}
pub fn pt_1(input: String) {
let #(left, right) =
input
|> string.split(on: "\n")
|> list.map(fn(line) {
let sections =
line
|> string.split(" ")
let left =
list.first(sections)
|> result.unwrap("0")
|> int.parse()
|> result.unwrap(0)
let right =
list.last(sections)
|> result.unwrap("0")
|> int.parse()
|> result.unwrap(0)
#(left, right)
})
|> list.unzip
let left = list.sort(left, by: int.compare)
let right = list.sort(right, by: int.compare)
solve_part_one(left, right, 0)
}
pub fn get_frequencies(
values: List(Int),
accum: dict.Dict(Int, Int),
) -> dict.Dict(Int, Int) {
case values {
[item, ..rest] -> {
let accum =
accum
|> dict.upsert(item, fn(x) {
case x {
option.Some(i) -> {
i + 1
}
option.None -> 1
}
})
get_frequencies(rest, accum)
}
_ -> accum
}
}
pub fn pt_2(input: String) {
let #(left, right) =
input
|> string.split(on: "\n")
|> list.map(fn(line) {
let sections =
line
|> string.split(" ")
let left =
list.first(sections)
|> result.unwrap("0")
|> int.parse()
|> result.unwrap(0)
let right =
list.last(sections)
|> result.unwrap("0")
|> int.parse()
|> result.unwrap(0)
#(left, right)
})
|> list.unzip
let frequencies = get_frequencies(right, dict.new())
left
|> list.fold(0, fn(current, value) {
let exists =
frequencies
|> dict.get(value)
|> result.unwrap(0)
current + { value * exists }
})
}