점 P(x, y) 와 선 AB (점 A(x_1, y_1) , 점 B(x_2, y_2) )가 주어졌을 때, 점 P 가 선분 AB 의 왼쪽에 있는지, 오른쪽에 있는지 또는 선 위에 있는지를 판단할 수 있습니다.
이를 위해 벡터 \overrightarrow{AB} 와 \overrightarrow{AP} 의 외적을 사용합니다.
외적의 값은 다음과 같이 계산됩니다.
이 값의 의미는 다음과 같습니다.
• 양수(+) : 점 P 가 선 AB 의 왼쪽에 있음
• 0 : 점 P 가 선 AB 위에 있음
• 음수(-) : 점 P 가 선 AB 의 오른쪽에 있음
data class Point(val x: Double, val y: Double)
fun crossProduct(A: Point, B: Point, P: Point): Double {
return (B.x - A.x) * (P.y - A.y) - (B.y - A.y) * (P.x - A.x)
}
fun pointRelativeToLine(A: Point, B: Point, P: Point): String {
val cross = crossProduct(A, B, P)
return when {
cross > 0 -> "Point is on the left of the line"
cross < 0 -> "Point is on the right of the line"
else -> "Point is on the line"
}
}
fun main() {
val A = Point(0.0, 0.0)
val B = Point(4.0, 4.0)
val P1 = Point(2.0, 3.0) // Left of the line
val P2 = Point(2.0, 1.0) // Right of the line
val P3 = Point(2.0, 2.0) // On the line
println(pointRelativeToLine(A, B, P1)) // Point is on the left of the line
println(pointRelativeToLine(A, B, P2)) // Point is on the right of the line
println(pointRelativeToLine(A, B, P3)) // Point is on the line
}
출처