Skip to content

Instantly share code, notes, and snippets.

@rranelli
Created February 5, 2019 21:37
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 rranelli/ec969ea1f9ef2bd3691fc905e0bd7b20 to your computer and use it in GitHub Desktop.
Save rranelli/ec969ea1f9ef2bd3691fc905e0bd7b20 to your computer and use it in GitHub Desktop.
defmodule Pentabonacci do
import Integer, only: [is_odd: 1]
defp calc(0, _), do: 0
defp calc(1, _), do: 1
defp calc(2, _), do: 1
defp calc(3, _), do: 2
defp calc(4, _), do: 4
defp calc(n, ets) do
case :ets.lookup(ets, n) do
[{_, cached_result}] ->
IO.puts("got cached #{cached_result}")
cached_result
_otherwise ->
IO.puts("calculating #{n}")
result = calc(n - 1, ets) + calc(n - 2, ets) + calc(n - 3, ets) + calc(n - 4, ets)
IO.puts("inserting #{n} -> #{result}")
:ets.insert(ets, {n, result})
result
end
end
def count_odd(n) do
ets = :ets.new(:qualquercoisa, [])
0..n
|> Enum.map(&calc(&1, ets))
|> Enum.count(&is_odd/1)
end
end
Pentabonacci.count_odd(10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment