Created
May 2, 2021 17:31
-
-
Save benmoss/8c278446b4e0d9beeee0aff38c73c181 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 ( | |
"fmt" | |
) | |
func fib(n int) int { | |
fibs := make(map[int]int, n+1) | |
fibs[0] = 0 | |
fibs[1] = 1 | |
var memFib func(n int, fibs map[int]int) int | |
memFib = func(n int, fibs map[int]int) int { | |
switch { | |
case n < 0: | |
panic("Don’t feed fib a negative number!") | |
default: | |
if f, ok := fibs[n]; ok { | |
return f | |
} | |
f := memFib(n-1, fibs) + memFib(n-2, fibs) | |
fibs[n] = f | |
return f | |
} | |
} | |
result := memFib(n, fibs) | |
return result | |
} | |
func fib2(n int) int { | |
switch { | |
case n < 0: | |
panic("Don’t feed fib a negative number!") | |
case n <= 1: | |
return n | |
default: | |
return fib2(n-1) + fib2(n-2) | |
} | |
} | |
func fib3(n int) int { | |
if n <= 1 { | |
return n | |
} | |
n2, n1 := 0, 1 | |
for i := 2; i < n; i++ { | |
n2, n1 = n1, n1+n2 | |
} | |
return n2 + n1 | |
} | |
func main() { | |
fmt.Printf("fib(50) = %d\n", fib(50)) | |
} |
This file contains hidden or 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 ( | |
"testing" | |
) | |
func BenchmarkFib(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
fib(50) | |
} | |
} | |
func BenchmarkFib2(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
fib2(50) | |
} | |
} | |
func BenchmarkFib3(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
fib3(50) | |
} | |
} |
Author
benmoss
commented
May 2, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment