this repo has no description
1
fork

Configure Feed

Select the types of activity you want to include in your feed.

use set for faster speed

estym 4d26f39c 2c49e199

+13 -15
+13 -15
src/days/day4.gleam
··· 2 2 import gleam/list 3 3 import gleam/option 4 4 import gleam/result 5 + import gleam/set 5 6 import gleam/string 6 7 import simplifile 7 8 ··· 14 15 } 15 16 16 17 type Grid { 17 - Grid(dim: Size, cells: List(Paper)) 18 + Grid(dim: Size, cells: set.Set(Paper)) 18 19 } 19 20 20 21 pub fn start() -> Nil { ··· 41 42 }) 42 43 }) 43 44 |> list.flatten 44 - |> list.filter(option.is_some) 45 - |> list.map(option.unwrap(_, Paper(-1, -1))) 45 + |> list.filter_map(option.to_result(_, Nil)) 46 + |> list.fold(set.new(), fn(acc, x) { set.insert(acc, x) }) 46 47 47 48 let dim = 48 49 Size( ··· 53 54 } 54 55 55 56 fn count_neighbours(cell: Paper, grid: Grid) { 56 - grid.cells 57 - |> list.filter(fn(paper) { 58 - !{ cell.x == paper.x && cell.y == paper.y } 59 - && { cell.x + 1 == paper.x || cell.x - 1 == paper.x || cell.x == paper.x } 60 - && { cell.y + 1 == paper.y || cell.y - 1 == paper.y || cell.y == paper.y } 57 + [#(-1, -1), #(-1, 0), #(-1, 1), #(0, -1), #(0, 1), #(1, -1), #(1, 0), #(1, 1)] 58 + |> list.filter(fn(offset) { 59 + set.contains(grid.cells, Paper(cell.x + offset.0, cell.y + offset.1)) 61 60 }) 62 61 |> list.length 63 62 } 64 63 65 64 fn part1(data: Grid) { 66 65 data.cells 66 + |> set.to_list 67 67 |> list.map(count_neighbours(_, data)) 68 68 |> list.filter(fn(x) { x < 4 }) 69 69 |> list.length 70 70 } 71 71 72 72 fn part2(data: Grid) { 73 - let to_remove = 73 + let to_keep = 74 74 data.cells 75 - |> list.filter(fn(x) { count_neighbours(x, data) < 4 }) 75 + |> set.filter(fn(x) { count_neighbours(x, data) >= 4 }) 76 + let to_remove = set.size(data.cells) - set.size(to_keep) 76 77 77 - case list.length(to_remove) { 78 + case to_remove { 78 79 0 -> 0 79 80 x -> { 80 - let new = 81 - data.cells 82 - |> list.filter(fn(x) { !list.contains(to_remove, x) }) 83 - x + part2(Grid(data.dim, new)) 81 + x + part2(Grid(data.dim, to_keep)) 84 82 } 85 83 } 86 84 }