my solutions to advent of code
aoc
advent-of-code
1import gleam/bit_array
2import gleam/int
3import gleam/io
4import gleam/list
5import gleam/result
6import gleam/string
7import simplifile as file
8
9fn generation(input: BitArray, size: Int, stuck: Bool) {
10 let get_place = fn(x, y) {
11 case
12 case stuck, x, y {
13 True, 0, 0 -> <<"#">>
14 True, 0, s | True, s, 0 if s == size - 1 -> <<"#">>
15 True, s1, s2 if s1 == size - 1 && s1 == s2 -> <<"#">>
16
17 _, _, -1 | _, -1, _ -> <<>>
18 _, s, _ | _, _, s if s == size -> <<>>
19
20 _, _, _ ->
21 bit_array.slice(input, y * size + x, 1) |> result.unwrap(<<>>)
22 }
23 {
24 <<"#">> -> 1
25 _ -> 0
26 }
27 }
28
29 list.range(0, bit_array.byte_size(input) - 1)
30 |> list.fold(<<>>, fn(res, pos) {
31 let x = pos % size
32 let y = pos / size
33
34 let cell = get_place(x, y)
35
36 let neighbours =
37 get_place(x - 1, y - 1)
38 + get_place(x, y - 1)
39 + get_place(x + 1, y - 1)
40 + get_place(x - 1, y)
41 + get_place(x + 1, y)
42 + get_place(x - 1, y + 1)
43 + get_place(x, y + 1)
44 + get_place(x + 1, y + 1)
45
46 bit_array.append(res, case stuck, x, y {
47 True, 0, 0 -> <<"#">>
48 True, 0, s | True, s, 0 if s == size - 1 -> <<"#">>
49 True, s1, s2 if s1 == size - 1 && s1 == s2 -> <<"#">>
50
51 _, _, _ ->
52 case cell, neighbours {
53 _, 3 | 1, 2 -> <<"#">>
54 _, _ -> <<".">>
55 }
56 })
57 })
58}
59
60fn check_lights_on(input: BitArray) {
61 list.range(0, bit_array.byte_size(input) - 1)
62 |> list.fold(0, fn(res, pos) {
63 let assert Ok(cell) = bit_array.slice(input, pos, 1)
64 case cell {
65 <<"#">> -> res + 1
66 _ -> res
67 }
68 })
69}
70
71pub fn main() {
72 let assert Ok(input) = file.read(from: "../input.txt")
73 as "Input file not found"
74 let input =
75 input |> string.trim |> string.split("\n") |> list.map(fn(v) { <<v:utf8>> })
76 let size = list.length(input)
77 let input = input |> list.fold(<<>>, fn(acc, l) { bit_array.append(acc, l) })
78
79 list.range(1, 100)
80 |> list.fold(input, fn(last, _) { generation(last, size, False) })
81 |> check_lights_on
82 |> int.to_string
83 |> io.println
84
85 list.range(1, 100)
86 |> list.fold(input, fn(last, _) { generation(last, size, True) })
87 |> check_lights_on
88 |> int.to_string
89 |> io.println
90}