2018-04-19 14:29:48 +03:00
|
|
|
package main
|
|
|
|
|
|
|
|
import "fmt"
|
|
|
|
|
2018-04-19 14:50:54 +03:00
|
|
|
type Memoized func(int) int
|
|
|
|
|
|
|
|
var fibMem = Memoize(fib)
|
|
|
|
|
|
|
|
func Memoize(mf Memoized) Memoized {
|
|
|
|
cache := make(map[int]int)
|
|
|
|
return func(key int) int {
|
|
|
|
if val, found := cache[key]; found {
|
|
|
|
return val
|
|
|
|
}
|
|
|
|
temp := mf(key)
|
|
|
|
cache[key] = temp
|
|
|
|
return temp
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func FibMemoized(n int) int {
|
|
|
|
return fibMem(n)
|
|
|
|
}
|
|
|
|
|
|
|
|
func fib(x int) int {
|
2018-04-19 14:29:48 +03:00
|
|
|
if x == 0 {
|
|
|
|
return 0
|
|
|
|
} else if x <= 2 {
|
|
|
|
return 1
|
|
|
|
} else {
|
2018-04-19 14:50:54 +03:00
|
|
|
return fib(x-2) + fib(x-1)
|
2018-04-19 14:29:48 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func main() {
|
2018-04-19 14:50:54 +03:00
|
|
|
fmt.Println(fib(30))
|
|
|
|
fmt.Println(FibMemoized(30))
|
2018-04-19 14:29:48 +03:00
|
|
|
}
|