Skip to content

Instantly share code, notes, and snippets.

@ragiragi
Created December 27, 2019 14:28
Show Gist options
  • Select an option

  • Save ragiragi/39d5b13c1b5c0f237f6f9e04d1317ebe to your computer and use it in GitHub Desktop.

Select an option

Save ragiragi/39d5b13c1b5c0f237f6f9e04d1317ebe to your computer and use it in GitHub Desktop.
Advent of Code 2019, Day3 Part 2
defmodule Day3Part2 do
@central_port {0, 0}
def run() do
p1 = read_path()
p2 = read_path()
intersection(p1, p2)
|> Enum.reject(&central_port?/1)
|> Enum.map(fn pos ->
number_of_steps(p1, pos) + number_of_steps(p2, pos)
end)
|> Enum.min()
|> IO.puts()
end
def read_path() do
IO.read(:line)
|> String.trim()
|> path_of_line()
end
def path_of_line(line) do
line
|> String.split(",")
|> Enum.reduce([@central_port], fn <<direction::utf8, distance::binary>>, path ->
move(path, direction, String.to_integer(distance))
end)
|> Enum.reverse()
end
defp move(path, _, 0), do: path
defp move([{x, y} | _] = path, ?R, distance), do: move([{x + 1, y} | path], ?R, distance - 1)
defp move([{x, y} | _] = path, ?L, distance), do: move([{x - 1, y} | path], ?L, distance - 1)
defp move([{x, y} | _] = path, ?U, distance), do: move([{x, y + 1} | path], ?U, distance - 1)
defp move([{x, y} | _] = path, ?D, distance), do: move([{x, y - 1} | path], ?D, distance - 1)
def intersection(p1, p2) do
MapSet.intersection(MapSet.new(p1), MapSet.new(p2))
|> MapSet.to_list()
end
defp central_port?(coord), do: @central_port == coord
def number_of_steps(path, target, steps \\ 0)
def number_of_steps([{x, y} | _], {x, y}, steps), do: steps
def number_of_steps([_h | t], target, steps), do: number_of_steps(t, target, steps + 1)
end
Day3Part2.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment