-
-
Save kwando/b444676070175d3180a0f53333717b1c to your computer and use it in GitHub Desktop.
AoC 2017 Day 19
This file contains 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 AoC.Day19 do | |
def part1(map) do | |
walk(map, find_start(map), {0, 1}, [], 0) | |
end | |
def walk(map, pos, dir, letters, steps) do | |
case map[pos] do | |
nil -> | |
{Enum.reverse(letters) |> Enum.join, steps} | |
x when x in ["|", "-"] -> | |
walk(map, next_pos(pos, dir), dir, letters, steps + 1) | |
"+" -> | |
dir = find_new_direction(map, pos, dir) | |
walk(map, next_pos(pos, dir), dir, letters, steps + 1) | |
letter -> | |
walk(map, next_pos(pos, dir), dir, [letter | letters], steps + 1) | |
end | |
end | |
@directions [{1, 0}, {0, 1}, {-1, 0}, {0, -1}] | |
defp find_new_direction(map, position, current_direction) do | |
[{_, direction}] = @directions | |
|> Enum.filter(&( &1 != reverse(current_direction) )) | |
|> Enum.map(&( {map[next_pos(position, &1)], &1})) | |
|> Enum.reject(&match?({nil, _}, &1)) | |
direction | |
end | |
defp next_pos({x1, y1}, {x2, y2}), do: {x1 + x2, y1 + y2} | |
defp reverse({x, y}), do: {-x, -y} | |
defp find_start(map) do | |
map | |
|> Enum.filter(&match?({{_, 0}, _}, &1)) | |
|> case do | |
[{start_coord, "|"}] -> start_coord | |
end | |
end | |
def build_map(file) do | |
file | |
|> File.stream!() | |
|> Stream.with_index | |
|> Enum.reduce(%{}, fn({line, row}, map)-> | |
line | |
|> String.trim_trailing("\n") | |
|> String.codepoints | |
|> Enum.with_index | |
|> Enum.reduce(map, fn | |
({" ", _}, map) | |
-> map | |
({cell, index}, map) | |
-> Map.put(map, {index, row}, cell) | |
end) | |
end) | |
end | |
end | |
System.argv | |
|> List.first | |
|> AoC.Day19.build_map() | |
|> AoC.Day19.part1() | |
|> IO.inspect(label: "result") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment