Files
aoc2021/six/lanternfish.go
2021-12-06 14:08:30 +00:00

66 lines
1.0 KiB
Go

package six
import (
"bufio"
"os"
"strconv"
"strings"
)
type lanternfish struct {
fish map[int]int
population int
}
func (l *lanternfish) load(filename string) error {
file, err := os.Open(filename)
if err != nil {
return err
}
defer file.Close()
scanner := bufio.NewScanner(file)
l.fish = map[int]int{}
for scanner.Scan() {
fishes := strings.Split(scanner.Text(), ",")
for _, fishy := range fishes {
f, err := strconv.Atoi(fishy)
if err != nil {
return err
}
l.fish[f]++
}
}
for _, count := range l.fish {
l.population += count
}
return nil
}
func (l *lanternfish) simulate(days int) {
for i := 0; i < days; i++ {
// How many fish spawn today
newFish := l.fish[0]
// Advance spawn counts
for j := 0; j < 8; j++ {
l.fish[j] = l.fish[j+1]
}
// Reset spawning fish to 6 days
l.fish[6] += newFish
// Add new fish to day 8
l.fish[8] = newFish
population := 0
for _, count := range l.fish {
population += count
}
l.population = population
}
}