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 ( import (
"flag" "flag"
"log" "log"
"math/rand"
"os" "os"
"os/signal" "os/signal"
"runtime/pprof" "runtime/pprof"
@@ -15,6 +16,7 @@ import (
func main() { func main() {
cpuprofile := flag.String("cpuprofile", "", "write cpu profile to file") cpuprofile := flag.String("cpuprofile", "", "write cpu profile to file")
initrandom := flag.Bool("random", false, "initialize arena with random values")
flag.Parse() flag.Parse()
// Jeśli podano flagę cpuprofile, rozpocznij profilowanie // Jeśli podano flagę cpuprofile, rozpocznij profilowanie
@@ -29,15 +31,17 @@ func main() {
} }
defer pprof.StopCPUProfile() defer pprof.StopCPUProfile()
} }
game() game(*initrandom)
} }
func game() { func initArena(front gol.Arena, initRandom bool) {
// arenas - front one is printed, then new state is calculated into the back one if initRandom {
// next front and back are switched for y := range front {
front := gol.New(20, 40) for x := range front[y] {
back := gol.New(20, 40) front[y][x] = rand.Intn(2) == 1
}
}
} else {
// draw initial objects // draw initial objects
// glider // glider
front[0][3] = true front[0][3] = true
@@ -50,6 +54,16 @@ func game() {
front[16][21] = true front[16][21] = true
front[17][21] = true front[17][21] = true
front[18][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)
initArena(front, initrandom)
// catch interrupt signals // catch interrupt signals
sigs := make(chan os.Signal, 1) 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 { 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) ysize := len(a)
xsize := len(a[0]) xsize := len(a[0])
@@ -75,7 +69,11 @@ func (a Arena) countNeighbours(x, y int) int {
if a[ny][nx] { if a[ny][nx] {
count++ count++
} }
if count > 3 {
return false // early exit
} }
} }
return count }
iAmAlive := a[y][x]
return count == 3 || (iAmAlive && count == 2)
} }