feat: Add random arena initialization option and optimize cell life calculation with an early exit.

This commit is contained in:
2025-11-22 12:50:49 +01:00
parent 941b3b0f6c
commit f50b9232f3
2 changed files with 33 additions and 21 deletions

View File

@@ -3,6 +3,7 @@ package main
import (
"flag"
"log"
"math/rand"
"os"
"os/signal"
"runtime/pprof"
@@ -15,6 +16,7 @@ import (
func main() {
cpuprofile := flag.String("cpuprofile", "", "write cpu profile to file")
initrandom := flag.Bool("random", false, "initialize arena with random values")
flag.Parse()
// Jeśli podano flagę cpuprofile, rozpocznij profilowanie
@@ -29,27 +31,39 @@ func main() {
}
defer pprof.StopCPUProfile()
}
game()
game(*initrandom)
}
func game() {
func initArena(front gol.Arena, initRandom bool) {
if initRandom {
for y := range front {
for x := range front[y] {
front[y][x] = rand.Intn(2) == 1
}
}
} else {
// draw initial objects
// glider
front[0][3] = true
front[1][4] = true
front[2][2] = true
front[2][3] = true
front[2][4] = true
// cross
front[16][21] = true
front[17][21] = true
front[18][21] = true
}
}
func game(initrandom bool) {
// arenas - front one is printed, then new state is calculated into the back one
// next front and back are switched
front := gol.New(20, 40)
back := gol.New(20, 40)
// draw initial objects
// glider
front[0][3] = true
front[1][4] = true
front[2][2] = true
front[2][3] = true
front[2][4] = true
// cross
front[16][21] = true
front[17][21] = true
front[18][21] = true
initArena(front, initrandom)
// catch interrupt signals
sigs := make(chan os.Signal, 1)

View File

@@ -55,12 +55,6 @@ func (a Arena) NextGen(to Arena) {
}
func (a Arena) life(x, y int) bool {
neighbours := a.countNeighbours(x, y)
iAmAlive := a[y][x]
return neighbours == 3 || (iAmAlive && neighbours == 2)
}
func (a Arena) countNeighbours(x, y int) int {
ysize := len(a)
xsize := len(a[0])
@@ -75,7 +69,11 @@ func (a Arena) countNeighbours(x, y int) int {
if a[ny][nx] {
count++
}
if count > 3 {
return false // early exit
}
}
}
return count
iAmAlive := a[y][x]
return count == 3 || (iAmAlive && count == 2)
}