Created
May 10, 2021 20:11
-
-
Save kiambogo/eea0442b08e2be8141d7900f7459274c to your computer and use it in GitHub Desktop.
Go Fibonacci with Memoization
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
package main | |
import "log" | |
func main() { | |
assert(0, fib(0)) | |
assert(1, fib(1)) | |
assert(1, fib(2)) | |
assert(2, fib(3)) | |
assert(3, fib(4)) | |
assert(5, fib(5)) | |
assert(8, fib(6)) | |
assert(13, fib(7)) | |
assert(21, fib(8)) | |
} | |
func fib(n int) int { | |
cache := make(map[int]int) | |
return fibR(cache, n) | |
} | |
func fibR(cache map[int]int, n int) int { | |
if n <= 1 { | |
return n | |
} | |
if val, hit := cache[n]; hit { | |
return val | |
} | |
cache[n] = fibR(cache, n-1) + fibR(cache, n-2) | |
return cache[n] | |
} | |
func assert(expected, actual interface{}) { | |
if expected != actual { | |
log.Panicf("%s != %s", expected, actual) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment