Last active
October 10, 2018 04:36
-
-
Save trbngr/3dfca9548bb35f0ae282cf146cc977d3 to your computer and use it in GitHub Desktop.
Knights Dialer in Elixir.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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