my solutions to advent of code
aoc
advent-of-code
1import gleam/dict
2import gleam/int
3import gleam/io
4import gleam/list
5import gleam/result
6import gleam/string
7import simplifile as file
8
9pub fn main() {
10 let assert Ok(right_sue) = file.read(from: "../sue.txt")
11 as "Sue file not found"
12 let right_sue =
13 right_sue
14 |> string.trim
15 |> string.split("\n")
16 |> list.map(fn(i) {
17 case string.split(i, " ") {
18 [item, amount] -> #(
19 string.drop_end(item, 1),
20 int.parse(amount) |> result.unwrap(0),
21 )
22 _ -> #("", 0)
23 }
24 })
25 |> dict.from_list
26
27 let assert Ok(input) = file.read(from: "../input.txt")
28 as "Input file not found"
29 let input =
30 input
31 |> string.trim
32 |> string.split("\n")
33 |> list.map(fn(i) {
34 case string.split(i, " ") {
35 [_, n, item1, amount1, item2, amount2, item3, amount3] -> #(
36 string.drop_end(n, 1) |> int.parse |> result.unwrap(0),
37 [
38 #(
39 string.drop_end(item1, 1),
40 string.drop_end(amount1, 1) |> int.parse |> result.unwrap(0),
41 ),
42 #(
43 string.drop_end(item2, 1),
44 string.drop_end(amount2, 1) |> int.parse |> result.unwrap(0),
45 ),
46 #(
47 string.drop_end(item3, 1),
48 amount3 |> int.parse |> result.unwrap(0),
49 ),
50 ],
51 )
52 _ -> #(0, [#("", 0), #("", 0), #("", 0)])
53 }
54 })
55 |> dict.from_list
56
57 // part 1
58 input
59 |> dict.fold(0, fn(right, sue, items) {
60 let total_right =
61 items
62 |> list.fold_until(0, fn(total_right, item) {
63 case item.1 == dict.get(right_sue, item.0) |> result.unwrap(-10) {
64 True -> list.Continue(total_right + 1)
65 False -> list.Stop(total_right)
66 }
67 })
68 case total_right {
69 3 -> sue
70 _ -> right
71 }
72 })
73 |> int.to_string
74 |> io.println
75
76 // part 2
77 input
78 |> dict.fold(0, fn(right, sue, items) {
79 let total_right =
80 items
81 |> list.fold_until(0, fn(total_right, item) {
82 let right_value = dict.get(right_sue, item.0) |> result.unwrap(-10)
83 let comp = case item.0 {
84 "cats" | "trees" -> item.1 > right_value
85 "pomeranians" | "goldfish" -> item.1 < right_value
86 _ -> item.1 == right_value
87 }
88 case comp {
89 True -> list.Continue(total_right + 1)
90 False -> list.Stop(total_right)
91 }
92 })
93 case total_right {
94 3 -> sue
95 _ -> right
96 }
97 })
98 |> int.to_string
99 |> io.println
100}