Skip to content

Instantly share code, notes, and snippets.

@manlon
Created December 4, 2017 01:06
Show Gist options
  • Save manlon/51bb550f73048d928035ddd3f105f60f to your computer and use it in GitHub Desktop.
Save manlon/51bb550f73048d928035ddd3f105f60f to your computer and use it in GitHub Desktop.
defmodule AoC3 do
def coord_stream do
directions = [{1,0}, {0,1}, {-1,0}, {0, -1}]
Stream.unfold({{0,0}, {0,0,0,0}, directions},
fn {{x,y}, {minx, miny, maxx, maxy}, dirs = [{dx,dy} | rest]} ->
{x_,y_} = {x+dx, y+dy}
{minx, miny, maxx, maxy, dirs} =
if (x_ > maxx) || (x_< minx) || (y_ > maxy) || (y_ < miny) do
{min(minx, x_), min(miny, y_), max(maxx, x_), max(maxy, y_), rest ++ [{dx,dy}]}
else
{minx, miny, maxx, maxy, dirs}
end
{{x_, y_}, {{x_, y_}, {minx, miny, maxx, maxy}, dirs}}
end)
end
def sums do
board = %{{0,0} => 1}
Stream.transform(coord_stream(), board, fn {x,y}, board ->
neighbors = for dx <- -1..1, dy <- -1..1, do: {x+dx, y+dy}
sum = neighbors |> Enum.map(fn n -> Map.get(board, n, 0) end) |> Enum.sum
{[sum], Map.put(board, {x,y}, sum)}
end)
end
def sums_until(n) do
sums()
|> Stream.transform(false, fn(x, hit) ->
if hit do
{:halt, x}
else
{[x], x > n}
end
end)
end
end
input = 277678
IO.inspect(AoC3.coord_stream |> Enum.at(input - 2) |> fn {x,y} -> abs(x) + abs(y) end.())
IO.inspect(AoC3.sums_until(input) |> Enum.at(-1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment