Day 8
This commit is contained in:
@@ -38,4 +38,7 @@ defmodule Aoc2023.Common do
|
||||
|
||||
def head([head | _]), do: head
|
||||
def tail([_ | tail]), do: tail
|
||||
|
||||
def lcm(a, b), do: div(abs(a*b), Integer.gcd(a,b))
|
||||
def lcm(ls), do: ls |> Enum.reduce(&lcm/2)
|
||||
end
|
||||
|
||||
39
lib/day8.ex
Normal file
39
lib/day8.ex
Normal file
@@ -0,0 +1,39 @@
|
||||
defmodule Aoc2023.Day8 do
|
||||
require Integer
|
||||
use Aoc2023
|
||||
|
||||
def parse(input) do
|
||||
input
|
||||
|> String.split("\n\n")
|
||||
|> then(fn [directions, map] ->
|
||||
{
|
||||
directions |> String.to_charlist() |> Enum.map(&%{?L => 0, ?R => 1}[&1]),
|
||||
map
|
||||
|> lines
|
||||
|> Enum.map(&Regex.run(~r/(\w+) = \((\w+), (\w+)\)/, &1, capture: :all_but_first))
|
||||
|> Enum.map(fn [src, dst1, dst2] -> {src, {dst1, dst2}} end)
|
||||
|> Enum.into(%{})
|
||||
}
|
||||
end)
|
||||
end
|
||||
|
||||
defp run({directions, map}, node, filter) do
|
||||
directions
|
||||
|> Stream.cycle()
|
||||
|> Stream.scan(node, fn dir, pos -> map[pos] |> elem(dir) end)
|
||||
|> Enum.find_index(filter)
|
||||
|> Kernel.+(1)
|
||||
end
|
||||
|
||||
def part1({directions, map}) do
|
||||
if map["AAA"], do: run({directions, map}, "AAA", &(&1 == "ZZZ"))
|
||||
end
|
||||
|
||||
def part2({directions, map}) do
|
||||
map
|
||||
|> Enum.map(pipe(elem(0)))
|
||||
|> Enum.filter(pipe(String.ends_with?("A")))
|
||||
|> Enum.map(&run({directions, map}, &1, pipe(String.ends_with?("Z"))))
|
||||
|> lcm
|
||||
end
|
||||
end
|
||||
@@ -9,6 +9,7 @@ defmodule Mix.Tasks.Aoc do
|
||||
defp module(5), do: Aoc2023.Day5
|
||||
defp module(6), do: Aoc2023.Day6
|
||||
defp module(7), do: Aoc2023.Day7
|
||||
defp module(8), do: Aoc2023.Day8
|
||||
# [MODULE INSERTION POINT]
|
||||
|
||||
defp base_dir(), do: System.get_env("AOC_BASE")
|
||||
@@ -16,7 +17,7 @@ defmodule Mix.Tasks.Aoc do
|
||||
defp tests(day) do
|
||||
case File.ls(tests_dir(day)) do
|
||||
{:ok, paths} ->
|
||||
paths |> Enum.filter(&(not String.contains?(&1, ".")))
|
||||
paths |> Enum.filter(&(not String.contains?(&1, "."))) |> Enum.sort
|
||||
|
||||
{:error, e} ->
|
||||
dbg(e)
|
||||
@@ -203,4 +204,4 @@ defmodule Mix.Tasks.Aoc do
|
||||
{:noreply, state}
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user