forked from Suryakant-Bharti/Important-Java-Concepts
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathGrahamScan.kt
54 lines (43 loc) Β· 1.59 KB
/
GrahamScan.kt
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
package algo.geometry.convexhull
import algo.datastructures.Stack
import algo.geometry.Point
class GrahamScan: ConvexHullAlgorithm {
override fun convexHull(points: Array<Point>): Collection<Point> {
if (points.size < 3) throw IllegalArgumentException("there must be at least 3 points")
val hull = Stack<Point>()
// Find the leftmost point
points.sortBy { it.y }
// Sort points by polar angle with p
points.sortWith( Comparator { q1, q2 ->
val dx1 = q1.x - points[0].x
val dy1 = q1.y - points[0].y
val dx2 = q2.x - points[0].x
val dy2 = q2.y - points[0].y
if (dy1 >= 0 && dy2 < 0)
-1 // q1 above; q2 below
else if (dy2 >= 0 && dy1 < 0)
+1 // q1 below; q2 above
else if (dy1 == 0 && dy2 == 0) { // 3-collinear and horizontal
if (dx1 >= 0 && dx2 < 0)
-1
else if (dx2 >= 0 && dx1 < 0)
+1
else
0
} else
-Point.orientation(points[0], q1, q2) // both above or below
// Note: ccw() recomputes dx1, dy1, dx2, and dy2
})
hull.push(points[0])
hull.push(points[1])
for (i in IntRange(2, points.size - 1)) {
var top = hull.poll()
while (Point.orientation(hull.peek(), top, points[i]) <= 0) {
top = hull.poll()
}
hull.push(top)
hull.push(points[i])
}
return hull
}
}