#!/usr/bin/env elixir defmodule Day10 do def part1({grid, zeros}) do zeros |> Enum.map(fn point -> MapSet.size(score(point, grid, 0)) end) |> Enum.sum() end def score(point, _grid, 9), do: MapSet.new([point]) def score({x, y}, grid, height) do find_neighbours(x, y, height, grid) |> Enum.map(fn {point, _} -> score(point, grid, height + 1) end) |> Enum.reduce(MapSet.new(), &MapSet.union/2) end def find_neighbours(x, y, height, grid) do next_height = height + 1 grid |> Map.take([{x - 1, y}, {x + 1, y}, {x, y - 1}, {x, y + 1}]) |> Enum.filter(&match?({_, ^next_height}, &1)) end def part2({grid, zeros}) do zeros |> Enum.map(fn point -> score2(point, grid, 0) end) |> Enum.sum() end def score2(_point, _grid, 9), do: 1 def score2({x, y}, grid, height) do find_neighbours(x, y, height, grid) |> Enum.map(fn {point, _} -> score2(point, grid, height + 1) end) |> Enum.sum() end def input do with [input_filename] <- System.argv(), {:ok, input} <- File.read(input_filename) do {grid, zeros, _, _, _} = for <>, reduce: {%{}, [], 0, 0, 0} do {grid, zeros, x, max_x, y} -> case char do "\n" -> {grid, zeros, 0, x, y + 1} "0" -> {Map.put(grid, {x, y}, 0), [{x, y} | zeros], x + 1, max_x, y} char -> {Map.put(grid, {x, y}, String.to_integer(char)), zeros, x + 1, max_x, y} end end {grid, zeros} else _ -> :error end end ####################### # HERE BE BOILERPLATE # ####################### def run do case input() do :error -> print_usage() input -> run_parts_with_timer(input) end end defp run_parts_with_timer(input) do run_with_timer(1, fn -> part1(input) end) run_with_timer(2, fn -> part2(input) end) end defp run_with_timer(part, fun) do {time, result} = :timer.tc(fun) IO.puts("Part #{part} (completed in #{format_time(time)}):\n") IO.puts("#{inspect(result)}\n") end defp format_time(μsec) when μsec < 1_000, do: "#{μsec}μs" defp format_time(μsec) when μsec < 1_000_000, do: "#{μsec / 1000}ms" defp format_time(μsec), do: "#{μsec / 1_000_000}s" defp print_usage do IO.puts("Usage: elixir day10.exs input_filename") end end Day10.run()