Skip to content

Instantly share code, notes, and snippets.

@sasa1977
Created December 19, 2017 08:28
Show Gist options
  • Save sasa1977/8dd2a3098480757536fb13d0d3c0e66f to your computer and use it in GitHub Desktop.
Save sasa1977/8dd2a3098480757536fb13d0d3c0e66f to your computer and use it in GitHub Desktop.
defmodule Day19 do
def part1(), do:
read_map() |> trip_steps() |> encountered_letters() |> Enum.to_list()
def part2(), do:
read_map() |> trip_steps() |> Enum.count()
defp encountered_letters(trip_steps), do:
trip_steps |> Stream.map(&Map.fetch!(&1.map, &1.pos)) |> Stream.reject(&(&1 in [?|, ?-, ?+]))
defp trip_steps(map), do:
map |> new_trip() |> Stream.iterate(&next_step/1) |> Stream.take_while(&(not is_nil(&1)))
defp new_trip(map), do:
%{map: map, pos: start_pos(map), direction: {1, 0}}
defp start_pos(map), do:
{0, 0 |> Stream.iterate(&(&1 + 1)) |> Enum.find(&Map.has_key?(map, {0, &1}))}
defp next_step(trip) do
with moves = possible_moves(trip.direction),
next_positions = Stream.map(moves, &{offset(trip.pos, &1), &1}),
{pos, direction} <- Enum.find(next_positions, fn {pos, _direction} -> Map.has_key?(trip.map, pos) end),
do: %{trip | pos: pos, direction: direction}
end
defp possible_moves({row, 0}), do: [{row, 0}, {0, 1}, {0, -1}]
defp possible_moves({0, col}), do: [{0, col}, {-1, 0}, {1, 0}]
defp offset({row, col}, {off_row, off_col}), do: {row + off_row, col + off_col}
defp read_map() do
for {line, row} <- "input.txt" |> File.stream!() |> Stream.with_index(),
line = String.trim_trailing(line),
{<<char::utf8>>, col} <- line |> String.codepoints() |> Stream.with_index(),
char != ?\s,
into: %{},
do: {{row, col}, char}
end
end
Day19.part1() |> IO.puts()
Day19.part2() |> IO.inspect()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment