chore: incorporate range over integers syntax

This commit is contained in:
Arek 2025-03-15 11:40:08 +01:00
parent 01a14fc5d1
commit 7a1ca2516c
2 changed files with 81 additions and 98 deletions

81
gol/arena.go Normal file
View File

@ -0,0 +1,81 @@
package gol
import (
"bytes"
"os"
"sync"
)
type Arena [][]bool
func New(ysize, xsize int) Arena {
var arena = make([][]bool, ysize)
for i := range ysize {
arena[i] = make([]bool, xsize)
}
return arena
}
// bufPool
var bufPool = sync.Pool{
New: func() any {
return new(bytes.Buffer)
},
}
var (
spriteOn = ([]byte)("\ue0b6\ue0b4")
spriteOff = ([]byte)("\u2022\u2022")
)
func (a Arena) PrintMe() {
b := bufPool.Get().(*bytes.Buffer)
b.Reset()
for i := range len(a) {
for j := range len(a[0]) {
if a[i][j] {
b.Write(spriteOn)
} else {
b.Write(spriteOff)
}
}
b.WriteRune('\n')
}
os.Stdout.Write(b.Bytes())
bufPool.Put(b)
}
func (a Arena) NextGen(to Arena) {
for y := range len(a) {
for x := range len(a[0]) {
to[y][x] = a.life(x, y)
}
}
}
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])
count := 0
for dy := -1; dy <= 1; dy++ {
for dx := -1; dx <= 1; dx++ {
if dx == 0 && dy == 0 {
continue
}
ny := (y + dy + ysize) % ysize
nx := (x + dx + xsize) % xsize
if a[ny][nx] {
count++
}
}
}
return count
}

View File

@ -1,98 +0,0 @@
package gol
import (
"bytes"
"os"
"sync"
)
type Arena [][]bool
func New(ysize, xsize int) Arena {
var arena = make([][]bool, ysize)
for i := 0; i < ysize; i++ {
arena[i] = make([]bool, xsize)
}
return arena
}
// bufPool
var bufPool = sync.Pool{
New: func() any {
return new(bytes.Buffer)
},
}
func (a Arena) PrintMe() {
b := bufPool.Get().(*bytes.Buffer)
b.Reset()
spriteOn := ([]byte)("\ue0b6\ue0b4")
spriteOff := ([]byte)("\u2022\u2022")
for i := 0; i < len(a); i++ {
for j := 0; j < len(a[0]); j++ {
if a[i][j] {
b.Write(spriteOn)
} else {
b.Write(spriteOff)
}
}
b.WriteRune('\n')
}
os.Stdout.Write(b.Bytes())
bufPool.Put(b)
}
func (a Arena) NextGen(to Arena) {
for y := 0; y < len(a); y++ {
for x := 0; x < len(a[0]); x++ {
to[y][x] = a.Life(x, y)
}
}
}
func (a Arena) Life(x, y int) bool {
count := a.countN(x, y)
current := a[y][x]
if !current && count == 3 {
return true
}
if current && (count == 2 || count == 3) {
return true
}
return false
}
type pair struct {
x int
y int
}
func (a Arena) countN(x, y int) int {
ysize := len(a)
xsize := len(a[0])
xb := (x - 1 + xsize) % xsize
xa := (x + 1 + xsize) % xsize
yb := (y - 1 + ysize) % ysize
ya := (y + 1 + ysize) % ysize
neigh := [8]pair{
{xb, yb},
{x, yb},
{xa, yb},
{xb, y},
{xa, y},
{xb, ya},
{x, ya},
{xa, ya},
}
count := 0
for _, p := range neigh {
if a[p.y][p.x] {
count++
}
}
return count
}