Last active
February 15, 2018 13:31
-
-
Save c-yan/6947e362b3cd26f95dd5577278459332 to your computer and use it in GitHub Desktop.
ackerman function with memoize
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" | |
| ) | |
| type AckParam struct { | |
| M uint64 | |
| N uint64 | |
| } | |
| func main() { | |
| var ( | |
| cache = make(map[AckParam]uint64) | |
| ack func(uint64, uint64) uint64 | |
| ) | |
| ack = func(m, n uint64) uint64 { | |
| k := AckParam{m, n} | |
| // /* | |
| if v, ok := cache[k]; ok { | |
| return v | |
| } | |
| // */ | |
| var result uint64 | |
| switch { | |
| case m == 0: | |
| result = n + 1 | |
| case n == 0: | |
| result = ack(m-1, 1) | |
| default: | |
| result = ack(m-1, ack(m, n-1)) | |
| } | |
| cache[k] = result | |
| return result | |
| } | |
| fmt.Println(ack(4, 1)) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment