Created
September 9, 2018 20:50
-
-
Save virtualtam/23550c9e734b1cb7a6a4aa3c0b2c967a to your computer and use it in GitHub Desktop.
Cellular Automaton - Ring of arrays with Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
import "container/ring" | |
import "math/rand" | |
type Cell struct { | |
alive bool | |
} | |
type Automaton struct { | |
size int | |
cells []Cell | |
} | |
func NewAutomaton(size int) Automaton { | |
a := Automaton{size: size} | |
a.cells = make([]Cell, a.size) | |
return a | |
} | |
func (a *Automaton) Randomize() { | |
for i := 0; i < len(a.cells); i++ { | |
a.cells[i].alive = rand.Intn(2) == 1 | |
} | |
} | |
type Buffer struct { | |
size int | |
automaton *Automaton | |
history *ring.Ring | |
} | |
func NewBuffer(size int, automaton *Automaton) Buffer { | |
b := Buffer{size: size, automaton: automaton} | |
b.history = ring.New(b.size) | |
for i := 0; i < b.history.Len(); i++ { | |
b.automaton.Randomize() | |
b.history.Value = make([]Cell, len(b.automaton.cells)) | |
copy(b.history.Value.([]Cell), b.automaton.cells) | |
b.history = b.history.Next() | |
} | |
return b | |
} | |
func (b *Buffer) Next() { | |
b.automaton.Randomize() | |
b.history.Value = make([]Cell, len(b.automaton.cells)) | |
copy(b.history.Value.([]Cell), b.automaton.cells) | |
b.history = b.history.Move(1) | |
} | |
func main() { | |
automaton := NewAutomaton(5) | |
automaton.Randomize() | |
buffer := NewBuffer(5, &automaton) | |
buffer.Next() | |
buffer.history.Do(func(p interface{}) { | |
fmt.Println(p) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment