纯记忆函数
使用闭包解决重复计算的性能开销
1.斐波纳列数列
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.整数转换成罗马数字
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()
})
}```
网友评论