From 613674a7daf9a521b4e38340f54a46279a882fce Mon Sep 17 00:00:00 2001 From: Nat Lasseter Date: Wed, 21 Feb 2018 09:04:45 +0000 Subject: Memoised fib --- fib.pr | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 fib.pr (limited to 'fib.pr') diff --git a/fib.pr b/fib.pr new file mode 100644 index 0000000..5d683ad --- /dev/null +++ b/fib.pr @@ -0,0 +1,42 @@ +#fib(0) is +# 1 +#end +#fib(1) is +# 1 +#end +#fib(n) is +# fib(n-1) + fib(n-2) +#end + +#puts fib(100) + +require 'yaml' +$memo = {} +if File.exists?("memofib.yaml") then + File.open("memofib.yaml", "r") do |f| + mem = YAML.load(f.read) + $memo = mem if mem + end +end + +memofib(0) is + 1 +end +memofib(1) is + 1 +end +memofib(n) is + if $memo.include?(n) then + $memo[n] + else + f = memofib(n-1) + memofib(n-2) + $memo[n] = f + end +end + +puts memofib(1000) + +File.open("memofib.yaml", "w") do |f| + f.write YAML.dump($memo) + f.flush +end -- cgit v1.2.1