## 2020年5月2日土曜日

### Go - コレクション - チャレンジ:ライフのスライス - 並行世界 - シミュレーションの完成、画面のクリア、Terminal

コード

```package main

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

const (
width  = 80
height = 24
)

type universe [][]bool

func newUniverse() universe {
u := make([][]bool, height, height)
for i := range u {
u[i] = make([]bool, width, width)
}
return u
}
func (u universe) set(i, j int, b bool) {
u[i][j] = b
}
func (u universe) alive(i, j int) bool {
return u[(i+height)%height][(j+width)%width]
}
func (u universe) seed() {
for i := 0; i < height; i++ {
for j := 0; j < width; j++ {
u.set(i, j, rand.Intn(100) <= 24)
}
}
}
func (u universe) neighbors(i, j int) int {
n := 0
for row := i - 1; row <= i+1; row++ {
for col := j - 1; col <= j+1; col++ {
if (row != i || row != col) && u.alive(row, col) {
n++
}
}
}
return n
}
func (u universe) next(i, j int) bool {
n := u.neighbors(i, j)
return n == 3 || (n == 2 && u.alive(i, j))
}
func (u universe) show() {
fmt.Print("\033[H")
for i := 0; i < height; i++ {
for j := 0; j < width; j++ {
if u.alive(i, j) {
fmt.Printf("*")
} else {
fmt.Printf(" ")
}
}
fmt.Println("")
}
}
func step(a, b universe) {
for i, row := range a {
for j := range row {
b.set(i, j, a.next(i, j))
}
}
}

func main() {
rand.Seed(time.Now().UnixNano())
u := newUniverse()
u.seed()
n := newUniverse()
for {
u.show()
step(u, n)
u, n = n, u
time.Sleep(time.Second / 2)
}
}
```