Skip to content

Instantly share code, notes, and snippets.

@trbngr
Last active October 10, 2018 04:36
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 trbngr/3dfca9548bb35f0ae282cf146cc977d3 to your computer and use it in GitHub Desktop.
Save trbngr/3dfca9548bb35f0ae282cf146cc977d3 to your computer and use it in GitHub Desktop.
Knights Dialer in Elixir.
defmodule KnightsDialer do
@nieghbors_map %{
1 => [6, 8],
2 => [7, 9],
3 => [4, 8],
4 => [3, 9, 0],
5 => [],
6 => [1, 7, 0],
7 => [2, 6],
8 => [1, 3],
9 => [2, 4],
0 => [4, 6]
}
def start, do: Agent.start_link(fn -> %{} end, name: __MODULE__)
defp get_cache(key), do: Agent.get(__MODULE__, &Map.get(&1, key))
defp put_cache(value, key) do
Agent.update(__MODULE__, &Map.put(&1, key, value))
value
end
def count_sequences(start, _) when start < 0 or start > 9 do
raise "Start should be bewteen 0 and 9"
end
def count_sequences(_start, 0), do: 1
def count_sequences(start, hops) do
case get_cache({start, hops}) do
nil ->
@nieghbors_map
|> Map.get(start)
|> Enum.reduce(0, fn next, total -> total + count_sequences(next, hops - 1) end)
|> put_cache({start, hops})
cached ->
cached
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment