this repo has no description

Day 4

+95
+2
src/aoc.gleam
··· 3 3 import days/day1 4 4 import days/day2 5 5 import days/day3 6 + import days/day4 6 7 import gleam/erlang 7 8 import gleam/int 8 9 import gleam/io ··· 25 26 1 -> day1.start() 26 27 2 -> day2.start() 27 28 3 -> day3.start() 29 + 4 -> day4.start() 28 30 _ -> io.println("Tried to run day " <> int.to_string(day)) 29 31 } 30 32 birl.now()
+93
src/days/day4.gleam
··· 1 + import gleam/dict 2 + import gleam/int 3 + import gleam/io 4 + import gleam/list 5 + import gleam/option 6 + import gleam/order 7 + import gleam/result 8 + import gleam/string 9 + import simplifile 10 + import utils/utils 11 + 12 + type Size { 13 + Size(height: Int, width: Int) 14 + } 15 + 16 + type Paper { 17 + Paper(x: Int, y: Int) 18 + } 19 + 20 + type Grid { 21 + Grid(dim: Size, cells: List(Paper)) 22 + } 23 + 24 + pub fn start() -> Nil { 25 + let assert Ok(content) = simplifile.read("inputs/day4.txt") 26 + let data = parse(content) 27 + 28 + let _ = io.debug(part1(data)) 29 + let _ = io.debug(part2(data)) 30 + 31 + Nil 32 + } 33 + 34 + fn parse(data: String) { 35 + let splitted = string.split(data, "\n") 36 + let papers = 37 + splitted 38 + |> list.index_map(fn(line, idx_height) { 39 + string.to_graphemes(line) 40 + |> list.index_map(fn(y, idx_width) { 41 + case y { 42 + "@" -> option.Some(Paper(idx_width, idx_height)) 43 + _ -> option.None 44 + } 45 + }) 46 + }) 47 + |> list.flatten 48 + |> list.filter(option.is_some) 49 + |> list.map(option.unwrap(_, Paper(-1, -1))) 50 + 51 + let dim = 52 + Size( 53 + list.length(splitted), 54 + list.first(splitted) |> result.unwrap("") |> string.length, 55 + ) 56 + Grid(dim, papers) 57 + } 58 + 59 + fn count_neighbours(cell: Paper, grid: Grid) { 60 + grid.cells 61 + |> list.filter(fn(paper) { !{ cell.x == paper.x && cell.y == paper.y } }) 62 + |> list.filter(fn(paper) { 63 + case cell.x + 1 == paper.x || cell.x - 1 == paper.x || cell.x == paper.x { 64 + True -> 65 + cell.y + 1 == paper.y || cell.y - 1 == paper.y || cell.y == paper.y 66 + False -> False 67 + } 68 + }) 69 + |> list.length 70 + } 71 + 72 + fn part1(data: Grid) { 73 + data.cells 74 + |> list.map(count_neighbours(_, data)) 75 + |> list.filter(fn(x) { x < 4 }) 76 + |> list.length 77 + } 78 + 79 + fn part2(data: Grid) { 80 + let to_remove = 81 + data.cells 82 + |> list.filter(fn(x) { count_neighbours(x, data) < 4 }) 83 + 84 + case list.length(to_remove) { 85 + 0 -> 0 86 + x -> { 87 + let new = 88 + data.cells 89 + |> list.filter(fn(x) { !list.contains(to_remove, x) }) 90 + x + part2(Grid(data.dim, new)) 91 + } 92 + } 93 + }