@@ -11,7 +11,7 @@ import (
11
11
//go:embed input.txt
12
12
var input string
13
13
14
- const simulateNDays = 256
14
+ const simulateNDays = 80
15
15
const eachFishReplicatesEveryNDays = 7
16
16
17
17
func main () {
@@ -20,15 +20,15 @@ func main() {
20
20
}
21
21
inputstrarr := strings .Split (input , "," )
22
22
world := & World {
23
- feesh : [] * Lanternfish {},
23
+ feesh : [eachFishReplicatesEveryNDays + 2 ] int {},
24
24
}
25
25
for _ , val := range inputstrarr {
26
26
n , err := strconv .Atoi (val )
27
27
if err != nil {
28
28
panic (err )
29
29
}
30
30
31
- world .feesh = append ( world .feesh , & Lanternfish { internaltimer : n })
31
+ world .feesh [ n ] = world .feesh [ n ] + 1
32
32
}
33
33
34
34
for i := 0 ; i < simulateNDays ; i ++ {
@@ -41,35 +41,30 @@ func main() {
41
41
fmt .Printf ("Answer: %d\n " , numberOfFish )
42
42
}
43
43
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.
46
46
47
- day int
47
+ type World struct {
48
+ feesh [eachFishReplicatesEveryNDays + 2 ]int
48
49
}
49
50
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
59
55
}
60
- w .feesh = append (w .feesh , newFeeshToAdd ... )
61
- w .day ++
62
- }
63
-
64
- type Lanternfish struct {
65
- internaltimer int
56
+ return count
66
57
}
67
58
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 ]
72
65
}
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 ())
75
70
}
0 commit comments