aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorNat Lasseter <Nat Lasseter user@4574.co.uk>2018-02-21 09:04:45 +0000
committerNat Lasseter <Nat Lasseter user@4574.co.uk>2018-02-21 09:04:45 +0000
commit613674a7daf9a521b4e38340f54a46279a882fce (patch)
tree27e6b3ff8f00309dbdfd1d4b826376729216b95b
parentdbb55f88451d27c4343da544e2a6577897bd7bd8 (diff)
Memoised fibHEADmaster
-rw-r--r--fib.pr42
1 files changed, 42 insertions, 0 deletions
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