Created
December 11, 2017 08:56
-
-
Save sasa1977/8515331714a9fe504eb86f04121430fd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Day11 do | |
def part1(), do: | |
start_pos() | |
|> positions(directions()) | |
|> last() | |
|> distance(start_pos()) | |
def part2(), do: | |
start_pos() | |
|> positions(directions()) | |
|> Stream.map(&distance(&1, start_pos())) | |
|> Enum.max() | |
def positions(start_pos, directions), do: | |
Stream.scan(directions, start_pos, &(&1 |> vector() |> add_points(&2))) | |
def directions(), do: | |
Stream.transform(File.stream!("input.txt", [], 1), "", &parse_char/2) | |
defp parse_char(delimiter, accumulated) when delimiter in [",", "\n"], do: | |
{[String.to_existing_atom(accumulated)], ""} | |
defp parse_char(other, accumulated), do: | |
{[], accumulated <> other} | |
defp start_pos(), do: | |
%{x: 0, y: 0, z: 0} | |
defp last(enumerable), do: | |
Enum.reduce(enumerable, nil, fn current_pos, _previous_pos -> current_pos end) | |
defp distance(p1, p2), do: | |
[p1.x - p2.x, p1.y - p2.y, p1.z - p2.z] |> Stream.map(&abs/1) |> Enum.max() | |
defp add_points(p1, p2), do: %{x: p1.x + p2.x, y: p1.y + p2.y, z: p1.z + p2.z} | |
defp vector(:n), do: %{x: 0, y: 1, z: -1} | |
defp vector(:ne), do: %{x: 1, y: 0, z: -1} | |
defp vector(:se), do: %{x: 1, y: -1, z: 0} | |
defp vector(:s), do: %{x: 0, y: -1, z: 1} | |
defp vector(:sw), do: %{x: -1, y: 0, z: 1} | |
defp vector(:nw), do: %{x: -1, y: 1, z: 0} | |
end | |
Day11.part1() |> IO.inspect | |
Day11.part2() |> IO.inspect |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment