-
Notifications
You must be signed in to change notification settings - Fork 0
/
coordinate.go
64 lines (57 loc) · 1.2 KB
/
coordinate.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
package coordinate_supplier
import (
"fmt"
"math/rand"
)
type Coordinate struct {
X int
Y int
}
// MakeCoordinateList returns a slice of Coordinate, with each item representing one cell in the XY grid.
// The Order determines the ordering of the coordinates in the slice.
func MakeCoordinateList(width, height int, order Order) (cs []Coordinate, err error) {
switch order {
case Asc:
cs = makeAscCoordinates(width, height)
case Random:
cs = makeAscCoordinates(width, height)
shuffleCoordinates(cs)
case Desc:
cs = makeAscCoordinates(width, height)
reverseCoordinates(cs)
default:
err = fmt.Errorf("unknown order specified")
}
return
}
func makeAscCoordinates(width, height int) []Coordinate {
coordinates := make([]Coordinate, 0, width*height)
var atX, atY int
for {
coordinates = append(coordinates, Coordinate{
X: atX,
Y: atY,
})
atX++
if atX >= width {
atX = 0
atY++
}
if atY >= height {
break
}
}
return coordinates
}
func reverseCoordinates(cs []Coordinate) {
i := 0
j := len(cs) - 1
for i < j {
cs[i], cs[j] = cs[j], cs[i]
i++
j--
}
}
func shuffleCoordinates(cs []Coordinate) {
rand.Shuffle(len(cs), func(i, j int) { cs[i], cs[j] = cs[j], cs[i] })
}