Skip to content

Instantly share code, notes, and snippets.

@bossek
Created December 16, 2020 20:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bossek/ec02ce15faf5aa11628e849830010c64 to your computer and use it in GitHub Desktop.
Save bossek/ec02ce15faf5aa11628e849830010c64 to your computer and use it in GitHub Desktop.
AoC 2020 Day 15 Part 2 - brute force without Enum.reduce
defmodule Day15Part2 do
def go do
261_214 = solve([1, 2, 3])
end
defp solve(already_spoken) do
start = Enum.count(already_spoken) + 1
stop = 30_000_000
spoken = :atomics.new(stop, [])
# Fill already spoken, n is stored with index n + 1 (atomics mem starts at 1).
Enum.each(Enum.with_index(already_spoken, 1), fn {n, turn} ->
:atomics.put(spoken, n + 1, turn)
end)
run(start, stop, Enum.at(already_spoken, -1), start - 1, spoken)
end
defp run(turn, stop, _last, before, spoken) when turn <= stop do
if before == turn - 1 do
before = :atomics.exchange(spoken, 0 + 1, turn)
run(turn + 1, stop, 0, (before == 0 && turn) || before, spoken)
else
n = turn - 1 - before
before = :atomics.exchange(spoken, n + 1, turn)
run(turn + 1, stop, n, (before == 0 && turn) || before, spoken)
end
end
defp run(turn, stop, last, _before, _spoken) when turn > stop do
last
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment