純記憶函數(shù)
使用閉包解決重復(fù)計算的性能開銷
1.斐波納列數(shù)列
type memoizeFunction func(int,...int) interface{}
var Fibonacci memoizeFunction
func init() {
Finonacci = Memoize(func (x int,xs ...int) interface{ }{
if x< 2{
return x
}
return Fibonacci(x-1).(int) + Fibonacci(x-2).(int)
} )
}```
func Memoize(function memoizeFunction) memoizeFunction {
cache := make(map[string] interface{})
return func(x int,xs ...int) interface{} {
key := fmt.Sprint(x)
for _,i := range xs {
key += fmt.Sprintf(",%d",i)
}
if value,found := cache[key];found {
return value;
}
value := function(x,xs....)
cache[key] = value
return value
}
}```
2.整數(shù)轉(zhuǎn)換成羅馬數(shù)字
var RomanForDecimal memoizeFunction
func init() {
decimail := [] int{1000,900,500,400,100,90,40,10,9,5,4,1}
romans :=[]string{"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}
RomanForDecimal = memoize(func(x int,xs ...int) interface{} {
if x<0 || x>3999 {
panic("RomanForDecimal() only handles integers [0,3999]")
}
var buffer bytes.Buffer
for i,decimal := range decimals {
remainder := x / decimal
x %= decimal
if remainder > 0 {
buffer.WriteString(strings.Repeat(romans[i],remainder))
}
}
return buffer.String()
})
}```