~hokiegeek/life

ref: c41a449353d445a06ec7334b540afb793d577cd8 life/pond.go -rw-r--r-- 7.9 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
package life

import (
	"bytes"
	"errors"
	"strconv"
)

// Location is a simple coordinate structure
type Location struct {
	X int
	Y int
}

// Equals is a basic equality test for the given object
func (t *Location) Equals(rhs *Location) bool {
	if t.X != rhs.X {
		return false
	}
	if t.Y != rhs.Y {
		return false
	}
	return true
}

func (t *Location) String() string {
	var buf bytes.Buffer
	buf.WriteString("[")
	buf.WriteString(strconv.Itoa(t.X))
	buf.WriteString(",")
	buf.WriteString(strconv.Itoa(t.Y))
	buf.WriteString("]")
	return buf.String()
}

// Dimensions is a simple structure capturing the given dimensions
type Dimensions struct {
	Width  int
	Height int
}

// Capacity returns the number of cells possible with the given dimensions
func (t *Dimensions) Capacity() int {
	return t.Width * t.Height
}

// Equals is a basic equality test for the given object
func (t *Dimensions) Equals(rhs *Dimensions) bool {
	if t.Width != rhs.Width {
		return false
	}

	if t.Height != rhs.Height {
		return false
	}

	return true
}

func (t *Dimensions) String() string {
	var buf bytes.Buffer
	buf.WriteString(strconv.Itoa(t.Width))
	buf.WriteString("x")
	buf.WriteString(strconv.Itoa(t.Height))
	return buf.String()
}

type neighborsSelector int

// Enumeration of the method to select neighbors
const (
	NeighborsAll neighborsSelector = iota
	NeighborsOrthogonal
	NeighborsOblique
)

func (t neighborsSelector) String() string {
	switch t {
	case NeighborsAll:
		return "All"
	case NeighborsOrthogonal:
		return "Orthogonal"
	case NeighborsOblique:
		return "Oblique"
	}
	return "Unknown"
}

type pond struct {
	Dims              Dimensions
	neighborsSelector neighborsSelector
	living            *tracker
}

func (t *pond) getOrthogonalNeighbors(location Location) []Location {
	neighbors := make([]Location, 0, 4)

	// Determine the offsets
	left := location.X - 1
	right := location.X + 1
	above := location.Y - 1
	below := location.Y + 1

	if above >= 0 {
		neighbors = append(neighbors, Location{X: location.X, Y: above})
	}

	if below < t.Dims.Height {
		neighbors = append(neighbors, Location{X: location.X, Y: below})
	}

	if left >= 0 {
		neighbors = append(neighbors, Location{X: left, Y: location.Y})
	}

	if right < t.Dims.Width {
		neighbors = append(neighbors, Location{X: right, Y: location.Y})
	}

	// fmt.Printf("GetOrthogonalNeighbors(%s): %v\n", location.String(), neighbors)
	return neighbors
}

func (t *pond) getObliqueNeighbors(location Location) []Location {
	neighbors := make([]Location, 0, 4)

	// Determine the offsets
	left := location.X - 1
	right := location.X + 1
	above := location.Y - 1
	below := location.Y + 1

	if above >= 0 {
		if left >= 0 {
			neighbors = append(neighbors, Location{X: left, Y: above})
		}
		if right < t.Dims.Width {
			neighbors = append(neighbors, Location{X: right, Y: above})
		}
	}

	if below < t.Dims.Height {
		if left >= 0 {
			neighbors = append(neighbors, Location{X: left, Y: below})
		}
		if right < t.Dims.Width {
			neighbors = append(neighbors, Location{X: right, Y: below})
		}
	}

	return neighbors
}

func (t *pond) getAllNeighbors(location Location) []Location {
	neighbors := append(t.getOrthogonalNeighbors(location), t.getObliqueNeighbors(location)...)

	return neighbors
}

func (t *pond) GetNeighbors(organism Location) ([]Location, error) {
	if !t.isValidLocation(organism) {
		return nil, errors.New("Location is out of bounds")
	}

	switch {
	case t.neighborsSelector == NeighborsOrthogonal:
		return t.getOrthogonalNeighbors(organism), nil
	case t.neighborsSelector == NeighborsOblique:
		return t.getObliqueNeighbors(organism), nil
	case t.neighborsSelector == NeighborsAll:
		return t.getAllNeighbors(organism), nil
	}

	return nil, errors.New("Did not recognize neighbor selector")
}

func (t *pond) numLivingOrthogonalNeighbors(location Location) (num int) {
	// Determine the offsets
	left := location.X - 1
	right := location.X + 1
	above := location.Y - 1
	below := location.Y + 1

	if above >= 0 && t.isOrganismAlive(Location{X: location.X, Y: above}) {
		num++
	}

	if below < t.Dims.Height && t.isOrganismAlive(Location{X: location.X, Y: below}) {
		num++
	}

	if left >= 0 && t.isOrganismAlive(Location{X: left, Y: location.Y}) {
		num++
	}

	if right < t.Dims.Width && t.isOrganismAlive(Location{X: right, Y: location.Y}) {
		num++
	}

	return
}

func (t *pond) numLivingObliqueNeighbors(location Location) (num int) {
	// Determine the offsets
	left := location.X - 1
	right := location.X + 1
	above := location.Y - 1
	below := location.Y + 1

	if above >= 0 {
		if left >= 0 && t.isOrganismAlive(Location{X: left, Y: above}) {
			num++
		}
		if right < t.Dims.Width && t.isOrganismAlive(Location{X: right, Y: above}) {
			num++
		}
	}

	if below < t.Dims.Height {
		if left >= 0 && t.isOrganismAlive(Location{X: left, Y: below}) {
			num++
		}
		if right < t.Dims.Width && t.isOrganismAlive(Location{X: right, Y: below}) {
			num++
		}
	}

	return
}

func (t *pond) NumLivingNeighbors(organism Location) (num int) {
	if !t.isValidLocation(organism) {
		return
	}

	switch {
	case t.neighborsSelector == NeighborsOrthogonal:
		return t.numLivingOrthogonalNeighbors(organism)
	case t.neighborsSelector == NeighborsOblique:
		return t.numLivingObliqueNeighbors(organism)
	case t.neighborsSelector == NeighborsAll:
		return t.numLivingOrthogonalNeighbors(organism) + t.numLivingObliqueNeighbors(organism)
	}

	return
}

func (t *pond) isValidLocation(location Location) bool {
	if location.X < 0 || location.X > t.Dims.Width {
		return false
	}
	if location.Y < 0 || location.Y > t.Dims.Height {
		return false
	}
	return true
}

func (t *pond) isOrganismAlive(organism Location) bool {
	return t.living.Test(organism)
}

func (t *pond) setOrganismState(organism Location, alive bool) {
	originalState := t.isOrganismAlive(organism)

	// Only do the deed if something has changed TODO: is this a stupid optimization?
	if originalState != alive {
		if alive {
			t.living.Set(organism)
		} else {
			t.living.Remove(organism)
		}
		// fmt.Printf("Living count is: %d\n", t.living.Count())
	}
}

func (t *pond) SetOrganisms(organisms []Location) {
	// Initialize the first organisms and set their neighbor counts
	for _, organism := range organisms {
		t.setOrganismState(organism, true)
	}
}

func (t *pond) Clone() (*pond, error) {
	shadowpond, err := newPond(t.Dims, t.living.Clone(), t.neighborsSelector)
	if err != nil {
		return nil, err
	}

	shadowpond.neighborsSelector = t.neighborsSelector

	shadowpond.SetOrganisms(t.living.GetAll())

	return shadowpond, nil
}

func (t *pond) Equals(rhs *pond) bool {
	if !t.living.Equals(rhs.living) {
		return false
	}
	if t.neighborsSelector != rhs.neighborsSelector {
		return false
	}
	return true
}

func (t *pond) String() string {
	var buf bytes.Buffer
	buf.WriteString("Neighbors: ")
	buf.WriteString(t.neighborsSelector.String())
	buf.WriteString("\tLiving cells: ")
	buf.WriteString(strconv.Itoa(t.living.Count()))
	buf.WriteString("\n")

	//// DRAW THE BOARD ////
	buf.WriteString("Size: ")
	buf.WriteString(t.Dims.String())
	buf.WriteString("\n")

	// Draw the top border
	buf.WriteString("┌")
	for j := t.Dims.Width; j > 0; j-- {
		buf.WriteString("─")
	}
	buf.WriteString("┐\n")

	// Draw out the matrix
	for y := 0; y < t.Dims.Height; y++ {
		buf.WriteString("│") // Left border
		for x := 0; x < t.Dims.Width; x++ {
			if t.isOrganismAlive(Location{X: x, Y: y}) {
				buf.WriteString("0")
			} else {
				buf.WriteString(" ")
			}
		}
		buf.WriteString("│\n") // Right border
	}

	// Draw the bottom border
	buf.WriteString("└")
	for j := t.Dims.Width; j > 0; j-- {
		buf.WriteString("─")
	}
	buf.WriteString("┘\n")

	return buf.String()
}

func newPond(dims Dimensions, tracker *tracker, neighbors neighborsSelector) (*pond, error) {
	if dims.Capacity() == 0 {
		return nil, errors.New("Cannot create pond of zero capacity")
	}

	p := new(pond)

	if tracker == nil {
		return nil, errors.New("tracker cannot be nil")
	}

	p.living = tracker
	p.neighborsSelector = neighbors

	p.Dims = dims

	return p, nil
}

// vim: set foldmethod=marker: