diff --git a/lib/common.ex b/lib/common.ex index 33d59a1..b30c0ea 100644 --- a/lib/common.ex +++ b/lib/common.ex @@ -45,4 +45,6 @@ defmodule Aoc2023.Common do def list_map_at(l, n, f) do List.replace_at(l, n, f.(Enum.at(l, n))) end + + def transpose(l), do: l |> Enum.zip |> Enum.map(&Tuple.to_list/1) end diff --git a/lib/day11.ex b/lib/day11.ex new file mode 100644 index 0000000..1d5884f --- /dev/null +++ b/lib/day11.ex @@ -0,0 +1,48 @@ +defmodule Aoc2023.Day11 do + use Aoc2023 + + def parse(input) do + coords = + input + |> lines + |> Enum.map(pipe(String.to_charlist() |> Enum.map(&(&1 == ?#)))) + |> Enum.with_index() + |> Enum.flat_map(fn {row, y} -> + row + |> Enum.with_index() + |> Enum.filter(pipe(elem(0))) + |> Enum.map(fn {_, x} -> {y, x} end) + end) + + ys = coords |> Enum.map(pipe(elem(0))) |> MapSet.new() + empty_rows = MapSet.difference(MapSet.new(0..(ys |> Enum.max())), ys) + xs = coords |> Enum.map(pipe(elem(1))) |> MapSet.new() + empty_cols = MapSet.difference(MapSet.new(0..(xs |> Enum.max())), xs) + fn expansion -> + coords_ = + coords + |> Enum.map(fn {y, x} -> + {y + Enum.count(empty_rows, &(&1 < y)) * (expansion - 1), + x + Enum.count(empty_cols, &(&1 < x)) * (expansion - 1)} + end) + + coords_ + |> Enum.with_index() + |> Enum.flat_map(fn {c, i} -> coords_ |> Enum.drop(i + 1) |> Enum.map(&{c, &1}) end) + |> Enum.map(&dist/1) + |> Enum.sum() + end + end + + defp dist({{y1, x1}, {y2, x2}}) do + abs(x1 - x2) + abs(y1 - y2) + end + + def part1(input) do + input.(2) + end + + def part2(input) do + input.(1_000_000) + end +end diff --git a/lib/mix_tasks.ex b/lib/mix_tasks.ex index 111cb80..acdc81b 100644 --- a/lib/mix_tasks.ex +++ b/lib/mix_tasks.ex @@ -12,6 +12,7 @@ defmodule Mix.Tasks.Aoc do defp module(8), do: Aoc2023.Day8 defp module(9), do: Aoc2023.Day9 defp module(10), do: Aoc2023.Day10 + defp module(11), do: Aoc2023.Day11 # [MODULE INSERTION POINT] defp base_dir(), do: System.get_env("AOC_BASE") diff --git a/tests/day11/1 b/tests/day11/1 new file mode 100644 index 0000000..986aad4 --- /dev/null +++ b/tests/day11/1 @@ -0,0 +1,10 @@ +...#...... +.......#.. +#......... +.......... +......#... +.#........ +.........# +.......... +.......#.. +#...#..... diff --git a/tests/day11/1.1 b/tests/day11/1.1 new file mode 100644 index 0000000..38a45c3 --- /dev/null +++ b/tests/day11/1.1 @@ -0,0 +1 @@ +374