Skip to content

Instantly share code, notes, and snippets.

@ynonp
Last active December 15, 2020 20:24
Show Gist options
  • Save ynonp/1ddfa5b494adf0f20d25adab6d402d5e to your computer and use it in GitHub Desktop.
Save ynonp/1ddfa5b494adf0f20d25adab6d402d5e to your computer and use it in GitHub Desktop.
defmodule Day15 do
def play(%{ :history => history, :last_value => value, :last_index => index }) do
next_history = seen(history, value, index)
next_value = get_value(next_history, value)
%{
:history => next_history,
:last_index => index + 1,
:last_value => next_value,
}
end
def seen(history, value, index) do
Map.update(history, value, [index, nil], fn
[idx1, nil] -> [index, idx1]
[idx1, idx2] -> [index, idx1]
end)
end
def get_value(history, value) do
case Map.get(history, value) do
[idx1, nil] -> 0
[idx1, idx2] -> idx1 - idx2
end
end
def make_history(values) do
values
|> Enum.with_index
|> Enum.map(fn { val, idx } -> %{ val => [idx + 1, nil] } end)
|> Enum.reduce(&Map.merge/2)
end
def read_input(values) do
last_value = values |> Enum.take(-1) |> Enum.at(0)
last_index = values |> Enum.count
%{
:history => make_history(values),
:last_value => last_value,
:last_index => last_index,
}
end
def part1 do
read_input([5,1,9,18,13,8,0])
|> Stream.iterate(&play/1)
|> Enum.find(fn %{:last_index => last_index} -> last_index == 30000000 end)
|> IO.inspect
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment