-
Notifications
You must be signed in to change notification settings - Fork 0
/
point.swift
65 lines (53 loc) · 1.71 KB
/
point.swift
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
struct Point: Hashable {
let x: Int
let y: Int
init(_ x: Int, _ y: Int) {
self.x = x
self.y = y
}
func getPointsAround(includingDiagonals: Bool = false) -> [Point] {
var points = [
Point(x, y - 1),
Point(x, y + 1),
Point(x - 1, y),
Point(x + 1, y),
]
if (includingDiagonals) {
points += [
Point(x - 1, y - 1),
Point(x + 1, y + 1),
Point(x - 1, y + 1),
Point(x + 1, y - 1),
]
}
return points
}
func getPointsBetween(_ point: Point) -> [Point] {
var points: [Point] = []
let start = self
let end = point
if (start.x == end.x) { // Vertical line
let x = start.x
let range = start.y > end.y ? end.y...start.y : start.y...end.y
for y in range {
points.append(Point(x, y))
}
} else if (start.y == end.y) { // Horizontal line
let y = start.y
let range = start.x > end.x ? end.x...start.x : start.x...end.x
for x in range {
points.append(Point(x, y))
}
} else { // Diagonal line
var xStep = start.x
var yStep = start.y
while Point(xStep, yStep) != end {
points.append(Point(xStep, yStep))
xStep += start.x < end.x ? 1 : -1
yStep += start.y < end.y ? 1 : -1
}
points.append(Point(xStep, yStep))
}
return points
}
}