~hokiegeek/life

ref: c41a449353d445a06ec7334b540afb793d577cd8 life/rules.go -rw-r--r-- 1.7 KiB View raw
c41a4493HokieGeek Refactored to host on sr.ht and converted to a mod 10 months ago
                                                                                
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
package life

import (
	"bytes"
	"strconv"
)

// Rules encapsulates the standard Life rules
type Rules struct {
	Survive []int // The number of neighbors an alive cell needs to have to survive
	Born    []int // The number of neighbors a dead cell needs to have to be born
}

func (t *Rules) String() string {
	var buf bytes.Buffer

	for _, val := range t.Survive {
		buf.WriteString(strconv.Itoa(val))
	}

	buf.WriteString("/")

	for _, val := range t.Born {
		buf.WriteString(strconv.Itoa(val))
	}

	return buf.String()
}

// This function tests the number of neighbors that a cell has against
// the rules given. If the cell lives (or continues to live) based on the
// rules, then the function returns true.
func testRule(numNeighbors int, isAlive bool, rules *Rules) bool {
	list := rules.Survive
	if !isAlive {
		list = rules.Born
	}

	for _, val := range list {
		if val == numNeighbors {
			return true
		}
	}

	return false
}

// RulesTester returns a RulesTest function that uses the given ruleset
func RulesTester(rules *Rules) func(int, bool) bool {
	return func(numNeighbors int, isAlive bool) bool {
		return testRule(numNeighbors, isAlive, rules)
	}
}

// GetConwayRules returns a Rules struct filled with the normal Conway rules of 23/3
//	-- Rules --
// 	1. If live cell has < 2 neighbors, it dies
// 	2. If live cell has 2 or 3 neighbors, it lives
// 	3. If live cell has > 3 neighbors, it dies
// 	4. If dead cell has exactly 3 neighbors, it lives
func GetConwayRules() *Rules {
	return &Rules{Survive: []int{2, 3}, Born: []int{3}}
}

// ConwayTester returns a rules tester with Conway Normal rules
func ConwayTester() func(int, bool) bool {
	return RulesTester(GetConwayRules())
}

// vim: set foldmethod=marker: