## 2020年2月2日日曜日

### Go - コレクション - ライフのスライス - Conway's Game of Life、セル・オートマトン、アルゴリズム

コード

```package main

import (
"fmt"
"math/rand"
"time"
)

const (
width  = 80
height = 24
)

// Universe ...
type Universe [][]bool

// NewUniverse ...
func NewUniverse() Universe {
u := make(Universe, height)
for i := range u {
u[i] = make([]bool, width)
}
return u
}

// Show ...
func (u Universe) Show() {
fmt.Print("\033[H")
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
if u.Alive(x, y) {
fmt.Print("*")
} else {
fmt.Print(" ")
}
}
fmt.Println()
}
}

// Seed ...
func (u Universe) Seed() {
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
u[y][x] = rand.Intn(2) == 0
}
}
}

// Alive ...
func (u Universe) Alive(x, y int) bool {
return u[(y+height)%height][(x+width)%width]
}

// Neighbors ...
func (u Universe) Neighbors(x, y int) int {
count := 0
for i := -1; i <= 1; i++ {
for j := -1; j <= 1; j++ {
if !(i == 0 && j == 0) && u.Alive(x+i, y+j) {
count++
}
}
}
return count
}

// Next ...
func (u Universe) Next(x, y int) bool {
count := u.Neighbors(x, y)
return count == 3 || (count == 2 && u.Alive(x, y))
}

// Step ...
func Step(a, b Universe) {
for y := range a {
for x := range a[y] {
b[y][x] = a.Next(x, y)
}
}
}

func main() {
u := NewUniverse()
uNext := NewUniverse()
u.Seed()
for {
u.Show()
time.Sleep(time.Second / 2)
Step(u, uNext)
u, uNext = uNext, u
}
}
```