-
-
Notifications
You must be signed in to change notification settings - Fork 358
Expand file tree
/
Copy pathjarvisMarch.scala
More file actions
60 lines (47 loc) · 1.44 KB
/
jarvisMarch.scala
File metadata and controls
60 lines (47 loc) · 1.44 KB
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
object GiftWrap {
case class Point(x: Int, y: Int)
def jarvisMarch(gift: List[Point]): List[Point] = {
def isClockwise(p1: Point, p2: Point, p3: Point): Boolean =
(p3.y - p1.y) * (p2.x - p1.x) >= (p2.y - p1.y) * (p3.x - p1.x)
def leastClockwise(apex: Point)(a: Point, b: Point): Point =
if (!isClockwise(apex, a, b)) a else b
def nextPointOnHull(current: Point): Point =
gift
.filter(_ != current) //ignore current point
.reduce(leastClockwise(current))
def leftmost(points: List[Point]): Point =
points.reduce((a, b) => if (a.x < b.x) a else b)
def buildHull(hull: List[Point]): List[Point] =
nextPointOnHull(hull.last) match {
case backToStart if backToStart == hull.head => hull
case nextPoint => buildHull(hull :+ nextPoint)
}
buildHull(List(leftmost(gift))) // leftmost point guaranteed to be in hull
}
def main(args: Array[String]): Unit = {
val testGift = List(
(-5, 2),
(-13, 100),
(5, 7),
(-6, -12),
(-14, -14),
(9, 9),
(-1, -1),
(20, 20),
(-10, 11),
(-13, 10),
(-6, 15),
(-6, -8),
(15, -9),
(7, -7),
(-2, -9),
(15, -15),
(6, -5),
(0, 14),
(2, 8)
).map({ case (x, y) => Point(x, y) })
val hull = jarvisMarch(testGift)
println("The points in the wrapping are:")
hull.foreach(println)
}
}