forked from Suryakant-Bharti/Important-Java-Concepts
-
Notifications
You must be signed in to change notification settings - Fork 17
/
Point.kt
52 lines (41 loc) Β· 1.61 KB
/
Point.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
package algo.geometry
data class Point(val x: Int, val y: Int): Comparable<Point> {
override fun compareTo(other: Point): Int {
if (x == other.x) return y.compareTo(other.y)
return x.compareTo(other.x)
}
fun isLeftOfLine(from: Point, to: Point): Boolean {
return crossProduct(from, to) > 0
}
fun crossProduct(origin: Point, p2: Point): Int {
return (p2.x - origin.x) * (this.y - origin.y) - (p2.y - origin.y) * (this.x - origin.x)
}
fun distanceToLine(a: Point, b: Point): Double {
return Math.abs((b.x - a.x) * (a.y - this.y) - (a.x - this.x) * (b.y - a.y)) /
Math.sqrt(Math.pow((b.x - a.x).toDouble(), 2.0) + Math.pow((b.y - a.y).toDouble(), 2.0))
}
fun euclideanDistanceTo(that: Point): Double {
return EUCLIDEAN_DISTANCE_FUNC(this, that)
}
fun manhattanDistanceTo(that: Point): Double {
return MANHATTAN_DISTANCE_FUNC(this, that)
}
companion object {
// < 0 : Counterclockwise
// = 0 : p, q and r are colinear
// > 0 : Clockwise
fun orientation(p: Point, q: Point, r: Point): Int {
return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y)
}
val EUCLIDEAN_DISTANCE_FUNC: (Point, Point) -> (Double) = { p, q ->
val dx = p.x - q.x
val dy = p.y - q.y
Math.sqrt((dx * dx + dy * dy).toDouble())
}
val MANHATTAN_DISTANCE_FUNC: (Point, Point) -> (Double) = { p, q ->
val dx = p.x - q.x
val dy = p.y - q.y
Math.sqrt((dx * dx + dy * dy).toDouble())
}
}
}