Created
December 7, 2021 22:35
-
-
Save gulliet/599a3e53ba5dc82f38bfa1268c7f637f to your computer and use it in GitHub Desktop.
Golang solution to AOC21 day6
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" | |
"log" | |
"os" | |
"strconv" | |
"strings" | |
) | |
func main() { | |
/* | |
Loading and formatting data | |
*/ | |
content, err := os.ReadFile("input.txt") | |
if err != nil { | |
log.Fatal(err) | |
} | |
s := string(content) | |
aux := strings.FieldsFunc(s, func(r rune) bool { return strings.ContainsRune(" ,\n", r) }) | |
var fish []int | |
for _, v := range aux { | |
n, err := strconv.Atoi(v) | |
if err != nil { | |
log.Fatal(err) | |
} | |
fish = append(fish, n) | |
} | |
/* | |
Main loop of the slice of fish. | |
Calling a recursive function with memoization (caching) | |
*/ | |
var res uint64 = 0 | |
comp := newMemoizedCompute() | |
for _, v := range fish { | |
res += comp(256, v) | |
} | |
fmt.Println("Final number of fish:", res) | |
} | |
func newMemoizedCompute() func(int, int) uint64 { | |
type key struct { | |
ttl int // Time to Live: when 0 no more processing | |
load int // Internal timer: before spanning new fish | |
} | |
cache := make(map[key]uint64) | |
var fn func(int, int) uint64 | |
fn = func(ttl int, load int) uint64 { | |
ttl = ttl - (load + 1) | |
if ttl < 0 { | |
return 1 | |
} | |
if _, ok := cache[key{ttl, load}]; !ok { | |
cache[key{ttl, load}] = fn(ttl, 6) + fn(ttl, 8) | |
} | |
return cache[key{ttl, load}] | |
} | |
return fn | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment