Last active
September 6, 2019 02:02
-
-
Save ProblemaResolt/a0ac334d336954059c5a9385f67f65de to your computer and use it in GitHub Desktop.
フィボナッチ数列の50番目をとるやつ For 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 Memorize do | |
def fib(0), do: 0 | |
def fib(1), do: 1 | |
def fib x do | |
case Agent.get(__MODULE__, &Map.get(&1, x)) do | |
nil -> | |
f = fib(x - 1) + fib(x - 2) | |
Agent.update(__MODULE__, &Map.put(&1, x, f)) | |
f | |
f -> f | |
end | |
end | |
def start_agent do | |
Agent.start_link &Map.new/0, name: __MODULE__ | |
end | |
end | |
Memorize.start_agent | |
Memorize.fib(50) | |
|> IO.inspect |
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 Memorize do | |
def fib 0 do | |
0 | |
end | |
def fib 1 do | |
1 | |
end | |
def fib x do | |
case Agent.get(:fib_memo, &Map.get(&1, x)) do | |
nil -> | |
v = fib(x - 1) + fib(x - 2) | |
Agent.update(:fib_memo, &Map.put(&1, x, v)) | |
v | |
v -> v | |
end | |
end | |
def start_agent do | |
Agent.start_link &Map.new/0, name: :fib_memo | |
end | |
end | |
Memorize.start_agent | |
IO.inspect Memorize.fib 100000 |
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 Fib do | |
def fib(0), do: 0 | |
def fib(1), do: 1 | |
def fib(n), do: fib(n - 1) + fib(n - 2) | |
end | |
Fib.fib(50) | |
|> IO.inspect |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment