Advent of Code 2024 - Day 10

Solving part2 first club++.

I guess the functional language forces us to think recursively, although I found it quite hard to reason about Part 1, it turned out I just needed to add a uniq call to the part 2 solution.

def part1({grid, zeros}) do
  zeros
  |> Enum.map(fn point -> point |> find_trails(grid, 0) |> Enum.uniq() |> Enum.count() end)
  |> Enum.sum()
end

def find_trails(point, _grid, 9), do: [point]

def find_trails({x, y}, grid, height) do
  find_neighbours(x, y, height + 1, grid)
  |> Enum.flat_map(fn {point, _} -> find_trails(point, grid, height + 1) end)
end

def find_neighbours(x, y, height, grid) do
  grid
  |> Map.take([{x - 1, y}, {x + 1, y}, {x, y - 1}, {x, y + 1}])
  |> Enum.filter(&match?({_, ^height}, &1))
end

https://git.adamu.jp/adam/AdventOfCode/src/branch/main/2024/day10.exs