Skip to content

Instantly share code, notes, and snippets.

@gulliet
Created December 7, 2021 22:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gulliet/599a3e53ba5dc82f38bfa1268c7f637f to your computer and use it in GitHub Desktop.
Save gulliet/599a3e53ba5dc82f38bfa1268c7f637f to your computer and use it in GitHub Desktop.
Golang solution to AOC21 day6
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