Skip to content

Instantly share code, notes, and snippets.

@rranelli
Created February 5, 2019 21:37
Show Gist options
  • Select an option

  • Save rranelli/6aef3a8a696da63fd1a6f0c70c8fb330 to your computer and use it in GitHub Desktop.

Select an option

Save rranelli/6aef3a8a696da63fd1a6f0c70c8fb330 to your computer and use it in GitHub Desktop.

Revisions

  1. rranelli created this gist Feb 5, 2019.
    36 changes: 36 additions & 0 deletions pentabonacci.ex
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,36 @@
    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)