10000 redoing part 1 so that it is efficient but constrained · jamesjarvis/adventofcode@3b3684b · GitHub
[go: up one dir, main page]

Skip to content

Commit 3b3684b

Browse files
committed
redoing part 1 so that it is efficient but constrained
1 parent 1a5aa7f commit 3b3684b

File tree

1 file changed

+22
-27
lines changed

1 file changed

+22
-27
lines changed

06/main.go

Lines changed: 22 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import (
1111
//go:embed input.txt
1212
var input string
1313

14-
const simulateNDays = 256
14+
const simulateNDays = 80
1515
const eachFishReplicatesEveryNDays = 7
1616

1717
func main() {
@@ -20,15 +20,15 @@ func main() {
2020
}
2121
inputstrarr := strings.Split(input, ",")
2222
world := &World{
23-
feesh: []*Lanternfish{},
23+
feesh: [eachFishReplicatesEveryNDays + 2]int{},
2424
}
2525
for _, val := range inputstrarr {
2626
n, err := strconv.Atoi(val)
2727
if err != nil {
2828
panic(err)
2929
}
3030

31-
world.feesh = append(world.feesh, &Lanternfish{internaltimer: n})
31+
world.feesh[n] = world.feesh[n] + 1
3232
}
3333

3434
for i := 0; i < simulateNDays; i++ {
@@ -41,35 +41,30 @@ func main() {
4141
fmt.Printf("Answer: %d\n", numberOfFish)
4242
}
4343

44-
type World struct {
45-
feesh []*Lanternfish
44+
// Represent fish lifetimes as an array of number of fish of length eachFishReplicatesEveryNDays + 2,
45+
// where the index of each element contains the count of fish at that age.
4646

47-
day int
47+
type World struct {
48+
feesh [eachFishReplicatesEveryNDays + 2]int
4849
}
4950

50-
func (w *World) Size() int { return len(w.feesh) }
51-
52-
func (w *World) Tick() {
53-
newFeeshToAdd := []*Lanternfish{}
54-
for _, lf := range w.feesh {
55-
newFeesh := lf.Tick()
56-
if newFeesh != nil {
57-
newFeeshToAdd = append(newFeeshToAdd, newFeesh)
58-
}
51+
func (w *World) Size() int {
52+
count := 0
53+
for _, numFish := range w.feesh {
54+
count += numFish
5955
}
60-
w.feesh = append(w.feesh, newFeeshToAdd...)
61-
w.day++
62-
}
63-
64-
type Lanternfish struct {
65-
internaltimer int
56+
return count
6657
}
6758

68-
func (lf *Lanternfish) Tick() *Lanternfish {
69-
if lf.internaltimer == 0 {
70-
lf.internaltimer = eachFishReplicatesEveryNDays - 1
71-
return &Lanternfish{eachFishReplicatesEveryNDays + 1}
59+
func (w *World) Tick() {
60+
fmt.Println("Number of fish before:", w.Size())
61+
resetFish := w.feesh[0]
62+
fmt.Println("Fish to reset:", resetFish)
63+
for day := 0; day < eachFishReplicatesEveryNDays-1; day++ {
64+
w.feesh[day] = w.feesh[day+1]
7265
}
73-
lf.internaltimer = lf.internaltimer - 1
74-
return nil
66+
w.feesh[eachFishReplicatesEveryNDays-1] = w.feesh[eachFishReplicatesEveryNDays] + resetFish
67+
w.feesh[eachFishReplicatesEveryNDays] = w.feesh[eachFishReplicatesEveryNDays+1]
68+
w.feesh[eachFishReplicatesEveryNDays+1] = resetFish
69+
fmt.Println("Number of fish after:", w.Size())
7570
}

0 commit comments

Comments
 (0)
0