/
ca.go
107 lines (88 loc) · 1.65 KB
/
ca.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package ca
import (
"crypto/rand"
"fmt"
"io"
"math/big"
)
var types = map[string]NewPrinter{}
func Register(key string, np NewPrinter) {
types[key] = np
}
var Default = Config{
Cells: 50,
Generations: 50,
Format: "txt",
Random: false,
Rule: 30,
Size: 5,
}
type Config struct {
Cells int
Generations int
Format string
Random bool
Rule int
Size int
}
func (c Config) Print(w io.Writer) error {
if c.Cells < 1 {
c.Cells = Default.Cells
}
if c.Generations < 1 {
c.Generations = Default.Generations
}
if c.Rule > 255 || c.Rule < 0 {
c.Rule = Default.Rule
}
r := rule(c.Rule)
if c.Size < 1 {
c.Size = Default.Size
}
np, ok := types[c.Format]
if !ok {
return fmt.Errorf("invalid type: %s", c.Format)
}
p := np(c.Cells, c.Generations, c.Size, w)
last := make([]bool, c.Cells, c.Cells)
next := make([]bool, c.Cells, c.Cells)
initialState(last, c.Random)
p.Print(last)
for i := 0; i < c.Generations; i++ {
for j := 0; j < c.Cells; j++ {
var l int8
if last[j] {
l |= 1 << 1
}
if j > 0 && last[j-1] {
l |= 1 << 2
}
if j < c.Cells-1 && last[j+1] {
l |= 1
}
next[j] = r.apply(l)
}
next, last = last, next
p.Print(last)
}
return p.Close()
}
var maxstate = new(big.Int).SetInt64(2)
func initialState(v []bool, randomize bool) {
if !randomize {
v[len(v)/2] = true
return
}
for i, _ := range v {
if r, err := rand.Int(rand.Reader, maxstate); err != nil {
panic(err)
} else {
v[i] = r.Int64() == 0
}
}
}
type rule int8
// Note: last must be between 0-8
func (r rule) apply(last int8) bool {
return (1<<byte(last))&r > 0
}