Skip to content

Instantly share code, notes, and snippets.

@ragiragi
Created December 8, 2019 07:55
Show Gist options
  • Select an option

  • Save ragiragi/2d4edbd786ec2aa21035d5b077fdf3c9 to your computer and use it in GitHub Desktop.

Select an option

Save ragiragi/2d4edbd786ec2aa21035d5b077fdf3c9 to your computer and use it in GitHub Desktop.
Advent of Code 2019, Day3 Part 1
defmodule Day3 do
@central_port {0, 0}
def run() do
p1 = read_path()
p2 = read_path()
intersection(p1, p2)
|> Enum.reject(&central_port?/1)
|> Enum.map(&manhattan_distance/1)
|> 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 manhattan_distance({x1, y1} \\ @central_port, {x2, y2}), do: abs(x2 - x1) + abs(y2 - y1)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment