this repo has no description

day 1

+126
+2
src/aoc.gleam
··· 1 1 import birl 2 2 import birl/duration 3 + import days/day1 3 4 import gleam/erlang 4 5 import gleam/int 5 6 import gleam/io ··· 19 20 let start = birl.now() 20 21 case day { 21 22 0 -> io.println_error("Invalid day") 23 + 1 -> day1.start() 22 24 _ -> io.println("Tried to run day " <> int.to_string(day)) 23 25 } 24 26 birl.now()
+124
src/days/day1.gleam
··· 1 + import gleam/dynamic 2 + import gleam/float 3 + import gleam/int 4 + import gleam/io 5 + import gleam/list 6 + import gleam/result 7 + import gleam/string 8 + import simplifile 9 + 10 + type Direction { 11 + Left 12 + Right 13 + } 14 + 15 + type Action { 16 + Action(Direction, Int) 17 + } 18 + 19 + pub fn start() -> Nil { 20 + let assert Ok(content) = simplifile.read("inputs/day1.txt") 21 + let data = parse(content) 22 + 23 + let _ = io.debug(part1(data)) 24 + let _ = io.debug(part2(data)) 25 + 26 + Nil 27 + } 28 + 29 + fn parse(data: String) { 30 + data 31 + |> string.split("\n") 32 + |> list.map(fn(l) { 33 + let chars = 34 + l 35 + |> string.to_graphemes() 36 + 37 + let direction_string = 38 + chars 39 + |> list.first 40 + |> result.unwrap("") 41 + 42 + let direction = case direction_string { 43 + "L" -> Left 44 + "R" -> Right 45 + _ -> Left 46 + } 47 + 48 + let number = 49 + chars 50 + |> list.drop(1) 51 + |> string.join("") 52 + |> int.parse 53 + |> result.unwrap(0) 54 + 55 + Action(direction, number) 56 + }) 57 + } 58 + 59 + fn part1(data: List(Action)) { 60 + data 61 + |> list.fold([50], fn(acc: List(Int), elem: Action) { 62 + let current = 63 + acc 64 + |> list.first 65 + |> result.unwrap(0) 66 + 67 + let new = case elem { 68 + Action(Left, x) -> { current - x } % 100 69 + Action(Right, x) -> { current + x } % 100 70 + } 71 + 72 + let new = case new < 0 { 73 + True -> new + 100 74 + False -> new 75 + } 76 + 77 + acc 78 + |> list.prepend(new) 79 + }) 80 + |> list.count(fn(x) { x == 0 }) 81 + } 82 + 83 + fn part2(data: List(Action)) { 84 + data 85 + |> list.fold([#(50, 0)], fn(acc: List(#(Int, Int)), elem: Action) { 86 + let #(current, _) = 87 + acc 88 + |> list.first 89 + |> result.unwrap(#(0, 0)) 90 + 91 + let Action(dir, clicks) = elem 92 + 93 + let remaining = clicks % 100 94 + 95 + let reached_zero = case dir { 96 + Left -> current - remaining <= 0 && current != 0 97 + Right -> current + remaining >= 100 && current != 0 98 + } 99 + 100 + let reached = 101 + { clicks / 100 } 102 + + case reached_zero { 103 + True -> 1 104 + False -> 0 105 + } 106 + 107 + let new = case elem { 108 + Action(Left, x) -> { current - x } % 100 109 + Action(Right, x) -> { current + x } % 100 110 + } 111 + 112 + let new = case new < 0 { 113 + True -> new + 100 114 + False -> new 115 + } 116 + 117 + acc 118 + |> list.prepend(#(new, reached)) 119 + }) 120 + |> list.fold(0, fn(acc, x) { 121 + let #(_, cnt) = x 122 + acc + cnt 123 + }) 124 + }