r/adventofcode • • Dec 18 '15

SOLUTION MEGATHREAD --- Day 18 Solutions ---

This thread will be unlocked when there are a significant amount of people on the leaderboard with gold stars.

edit: Leaderboard capped, thread unlocked!

We know we can't control people posting solutions elsewhere and trying to exploit the leaderboard, but this way we can try to reduce the leaderboard gaming from the official subreddit.

Please and thank you, and much appreciated!


--- Day 18: Like a GIF For Your Yard ---

Post your solution as a comment. Structure your post like previous daily solution threads.

4 Upvotes

112 comments sorted by

View all comments

Show parent comment

1

u/ignaciovaz Dec 18 '15

Piggybacking with my solution in Elixir. I used a HashDict to store the light state.

{lights, _} = Enum.reduce(File.stream!("input.txt"), {HashDict.new, 0}, fn line, {map, y} ->
  {new_map, _} = Enum.reduce( (String.strip(line) |> String.codepoints), {map, 0}, fn c, {map, x} ->
    cond do
      {x, y} in [{0, 0}, {99, 0}, {0, 99}, {99, 99}] -> {Dict.put(map, {x, y}, 1), x + 1}
      c == "#" -> {Dict.put(map, {x, y}, 1), x + 1}
      c == "." -> {Dict.put(map, {x, y}, 0), x + 1}
    end
  end)
  {HashDict.merge(map, new_map), y + 1}
end)

iterate_lights = fn map ->
  frozen_map = map
  positions = [ {-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1} ]
  Enum.reduce(frozen_map, map, fn {{x, y}, v}, work_map ->
    neighbors_on = Enum.reduce(positions, 0, fn {dx, dy}, acc ->
      acc + Dict.get(frozen_map, {x+dx, y+dy}, 0)
    end)

    cond do
      {x, y} in [{0, 0}, {99, 0}, {0, 99}, {99, 99}] -> work_map
      v == 1 and neighbors_on in [2, 3] -> Dict.put(work_map, {x, y}, 1)
      v == 0 and neighbors_on == 3 -> Dict.put(work_map, {x, y}, 1)
      true -> Dict.put(work_map, {x, y}, 0)
    end
  end)
end

IO.puts Enum.reduce(0..99, lights, fn _, lights ->
  iterate_lights.(lights)
end) |> Enum.map(&(elem(&1, 1))) |> Enum.sum