~hokiegeek/life

ref: c41a449353d445a06ec7334b540afb793d577cd8 life/tracker.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
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
package life

import "sync"

type tracker struct {
	mu        sync.RWMutex
	livingMap map[int]map[int]struct{}
	count     int
}

func (t *tracker) Set(location Location) (_ bool) {
	t.mu.Lock()
	defer t.mu.Unlock()

	if _, ok := t.livingMap[location.Y]; !ok {
		t.livingMap[location.Y] = make(map[int]struct{})
	}
	if _, ok := t.livingMap[location.Y][location.X]; !ok {
		t.livingMap[location.Y][location.X] = struct{}{}
		t.count++
		return true
	}

	return
}

func (t *tracker) Remove(location Location) (_ bool) {
	t.mu.Lock()
	defer t.mu.Unlock()

	if _, ok := t.livingMap[location.Y]; ok {
		if _, ok = t.livingMap[location.Y][location.X]; ok {
			delete(t.livingMap[location.Y], location.X)
			t.count--
			return true
		}
	}

	return
}

func (t *tracker) Test(location Location) (found bool) {
	t.mu.RLock()
	defer t.mu.RUnlock()

	if _, ok := t.livingMap[location.Y]; ok {
		_, found = t.livingMap[location.Y][location.X]
	}

	return
}

func (t *tracker) GetAll() []Location {
	t.mu.RLock()
	defer t.mu.RUnlock()

	all := make([]Location, 0, t.count)
	for y := range t.livingMap {
		for x := range t.livingMap[y] {
			// all = append(all, col)
			all = append(all, Location{X: x, Y: y})
		}
	}

	return all
}

func (t *tracker) Count() int {
	return t.count
}

func (t *tracker) Equals(rhs *tracker) bool {
	if t.Count() != rhs.Count() {
		return false
	}

	for _, loc := range t.GetAll() {
		if !rhs.Test(loc) {
			return false
		}
	}

	return true
}

func (t *tracker) Clone() *tracker {
	shadow := newTracker()

	for _, loc := range t.GetAll() {
		shadow.Set(loc)
	}

	return shadow
}

func newTracker() *tracker {
	t := new(tracker)

	t.livingMap = make(map[int]map[int]struct{})

	return t
}

// vim: set foldmethod=marker: