my solutions to advent of code
aoc
advent-of-code
1import gleam/dict.{type Dict}
2import gleam/int.{to_string}
3import gleam/io.{println}
4import gleam/list.{fold}
5import gleam/result.{unwrap}
6import gleam/string.{split, trim}
7import simplifile.{read}
8
9pub type Location {
10 Location(x: Int, y: Int)
11}
12
13pub type World =
14 Dict(Location, Int)
15
16pub type State {
17 State(location: Location, world: World)
18}
19
20pub type Turn {
21 Santa
22 Robo
23}
24
25pub type RoboState {
26 RoboState(
27 turn: Turn,
28 santa_location: Location,
29 robo_location: Location,
30 world: World,
31 )
32}
33
34pub fn give_gift(world: World, location: Location) {
35 dict.insert(world, location, { dict.get(world, location) |> unwrap(0) } + 1)
36}
37
38pub fn move_to(location: Location, direction: String) {
39 case direction {
40 "^" -> Location(location.x, location.y - 1)
41 "v" -> Location(location.x, location.y + 1)
42 "<" -> Location(location.x - 1, location.y)
43 ">" -> Location(location.x + 1, location.y)
44 ___ -> Location(location.x, location.y)
45 }
46}
47
48pub fn main() {
49 let input = read(from: "../input.txt") |> unwrap("") |> trim() |> split("")
50
51 // part 1
52 println(
53 {
54 input
55 |> fold(State(Location(0, 0), dict.new()), fn(state, direction) {
56 let loc = state.location
57 State(move_to(loc, direction), give_gift(state.world, loc))
58 })
59 }.world
60 |> dict.size()
61 |> to_string(),
62 )
63
64 // part 2
65 println(
66 {
67 input
68 |> fold(
69 RoboState(Santa, Location(0, 0), Location(0, 0), dict.new()),
70 fn(state, direction) {
71 let sloc = state.santa_location
72 let rloc = state.robo_location
73 case state.turn {
74 Santa ->
75 RoboState(
76 Robo,
77 move_to(sloc, direction),
78 Location(rloc.x, rloc.y),
79 give_gift(state.world, sloc),
80 )
81 Robo ->
82 RoboState(
83 Santa,
84 Location(sloc.x, sloc.y),
85 move_to(rloc, direction),
86 give_gift(state.world, rloc),
87 )
88 }
89 },
90 )
91 }.world
92 |> dict.size()
93 |> to_string(),
94 )
95}