import gleam/list import gleam/set import gleam/string import internal/grid.{type Vec2, Vec2} type Forest = set.Set(Vec2) pub fn solve_a(input: String) -> Int { count_squares(parse(input), fn(a, b) { b.y == a.y }) } pub fn solve_b(input: String) -> Int { count_squares(parse(input), fn(a, b) { b.y >= a.y }) } fn count_squares(forest: Forest, b_allowed: fn(Vec2, Vec2) -> Bool) -> Int { use total, a <- set.fold(forest, from: 0) let candidates = set.filter(forest, fn(b) { b.x > a.x && b_allowed(a, b) }) use total, b <- set.fold(candidates, from: total) case is_square(forest, a, b) { True -> total + 1 False -> total } } fn is_square(forest: Forest, a: Vec2, b: Vec2) -> Bool { let side = b.x - a.x let tilt = b.y - a.y let c = Vec2(b.x - tilt, b.y + side) let d = Vec2(a.x - tilt, a.y + side) set.contains(forest, c) && set.contains(forest, d) } fn parse(input: String) -> Forest { use forest, line, y <- list.index_fold(string.split(input, "\n"), set.new()) use forest, char, x <- list.index_fold(string.to_graphemes(line), forest) case char { "#" -> set.insert(forest, Vec2(x, y)) _ -> forest } }