From e4b27c9bc1266308888abd8decf7fb34ff55c6b9 Mon Sep 17 00:00:00 2001 From: Adam Millerchip Date: Tue, 10 Dec 2024 16:30:33 +0900 Subject: [PATCH] 2024 Day 10 --- 2024/day10.exs | 89 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 2024/day10.exs diff --git a/2024/day10.exs b/2024/day10.exs new file mode 100644 index 0000000..76d4d22 --- /dev/null +++ b/2024/day10.exs @@ -0,0 +1,89 @@ +#!/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()