import gleam/dict import gleam/int import gleam/io import gleam/list import gleam/order import gleam/string pub fn solve_a(program: String) -> Int { let grid = create_grid(string.split(program, "\n")) let size = get_size(grid) use grand_total, x <- int.range(0, size.0, with: 0) use subtotal, y <- int.range(0, size.1, with: grand_total) use count, distance <- int.range( from: 1, to: int.min(size.0 - x, size.1 - y) + 1, with: subtotal, ) case is_square(grid, x, y, distance) { True -> count + 1 False -> count } } pub fn solve_b(program: String) -> Int { // dy = 0 case let total_a = solve_a(program) // rotated cases let grid = create_grid(string.split(program, "\n")) let size = get_size(grid) use grand_total, x <- int.range(0, size.0, with: total_a) use subtotal, y <- int.range(0, size.1, with: grand_total) use count_x, dx <- int.range(from: 1, to: size.0, with: subtotal) use count, dy <- int.range(from: 1, to: size.1, with: count_x) case is_square_b(grid, x, y, dx, dy) { True -> { count + 1 } False -> count } } fn is_square( grid: dict.Dict(#(Int, Int), String), x: Int, y: Int, distance: Int, ) -> Bool { is_tree(grid, x, y) && is_tree(grid, x + distance, y) && is_tree(grid, x, y + distance) && is_tree(grid, x + distance, y + distance) } fn is_square_b( grid: dict.Dict(#(Int, Int), String), x: Int, y: Int, dx: Int, dy: Int, ) -> Bool { is_tree(grid, x, y) && is_tree(grid, x + dx, y + dy) && is_tree(grid, x + dx - dy, y + dy + dx) && is_tree(grid, x - dy, y + dx) } // .#... // ....# // ..... // #.... // ...#. fn is_tree(grid: dict.Dict(#(Int, Int), String), x: Int, y: Int) -> Bool { case dict.get(grid, #(x, y)) { Ok("#") -> True _ -> False } } fn get_size(grid: dict.Dict(#(Int, Int), String)) -> #(Int, Int) { let assert Ok(range) = dict.keys(grid) |> list.max(fn(a, b) { case int.compare(a.0, b.0) { order.Eq -> int.compare(a.1, b.1) otherwise -> otherwise } }) range } fn create_grid(lines: List(String)) -> dict.Dict(#(Int, Int), String) { let gs = lines |> list.map(string.to_graphemes) use grid, chars, y <- list.index_fold(gs, dict.new()) use grid, char, x <- list.index_fold(chars, grid) dict.insert(grid, #(x, y), char) } fn debug_grid(grid: dict.Dict(#(Int, Int), String), x: Int, y: Int) -> Nil { case dict.get(grid, #(x, y)), x { Ok(char), _ -> { io.print(char) debug_grid(grid, x + 1, y) } Error(_), 0 -> Nil Error(_), _ -> { io.println("") debug_grid(grid, 0, y + 1) } } }