如何在Java中檢查3個有序點的方向?
在這篇文章中,我們將找出3個有序點的方向。這裡的方向指的是給定的點在空間中形成順時針、逆時針或共線形狀。
在上圖中,a、b、c是三個檢查空間中形狀方向的點。我們透過計算斜率來找到三個給定點的方向。
計算斜率並計算3個有序點的方向。
線段的斜率
線段(a,b)的斜率:θ=(yb-ya)/(xb-xa)
線段(b,c)的斜率:φ=(yc-yb)/(xc-xb)
因此,方向取決於以下表達式
$$(y_{b}-y_{a})(x_{c}-x_{b})-(y_{c}-y_{b})(x_{b}-x_{a})\:或\:(y2-y1)*(x3-x2)-(y3-y2)*(x2-x1)$$
即,它是正數、負數還是
如果表示式為零,則θ = φ。因此方向是共線的。
如果表示式為負,則θ < φ。因此方向是逆時針的。
如果表示式為正,則θ > φ。因此方向是順時針的。
讓我們開始吧!
給你看一些例子
示例1
假設3個有序點是(0,3)、(4,2)、(3,1)
檢查3個有序點的方向後,結果將是
給定的3個點形成:順時針
示例2
假設3個有序點是(0,3)、(1,2)、(9,5)
檢查3個有序點的方向後,結果將是
給定的3個點形成:逆時針
示例3
假設3個有序點是(2,2)、(3,3)、(4,4)
檢查3個有序點的方向後,結果將是
給定的3個點形成:共線
演算法
步驟1 - 宣告3個有序點。
步驟2 - 將三個給定點傳遞給表示式,即(b.y - a.y) * (c.x - b.x) - (b.x - a.x) * (c.y - b.y)。
步驟3 - 檢查共線、順時針和逆時針的條件。
步驟4 - 列印結果。
多種方法
我們提供了不同方法的解決方案。
透過靜態輸入
透過使用使用者定義的方法
讓我們逐一檢視程式及其輸出。
方法1:使用靜態輸入
在這種方法中,首先將3個點傳遞給表示式,以檢查共線、順時針和逆時針的條件。然後將結果列印到輸出。
示例
public class Main{
//main method
public static void main(String[] args){
//Declaring variables
int x1=0, y1=1;
int x2=4, y2=3;
int x3=3, y3=2;
//expression to check for 3 ordered point
int val = (y2 - y1) * (x3 - x2) - (x2 - x1) * (y3 - y2);
// check for collinear
if (val == 0){
//printing collinear orientation
System.out.print("The given 3 points form : Linear");
}
//check for clockwise
else if(val > 0){
//printing clockwise orientation
System.out.print("The given 3 points form: Clockwise");
} else {
//printig counter clockwise orientation
System.out.print("The given 3 points form: CounterClockwise");
}
}
}
輸出
The given 3 points form: Clockwise
方法2:使用使用者定義的方法
在這種方法中,首先使用使用者定義的方法將3個點傳遞給表示式,以檢查共線、順時針和逆時針的條件。然後將結果列印到輸出。
示例
public class Main {
public static void main(String[] args){
Point a = new Point(2, 2);
Point b = new Point(3, 3);
Point c = new Point(4, 4);
//calling user defined method
int o = orientation(a, b, c);
//check for Linear orientation
if (o==0)
//printing Linear orientation
System.out.print("The given 3 points form : Linear");
//check for Clockwise orientation
else if (o == 1)
//printing clockwise orientation
System.out.print("The given 3 points form : Clockwise");
else
//printing counter clockwise orientation
System.out.print("The given 3 points form : CounterClockwise");
}
// user defined method
public static int orientation(Point a, Point b, Point c){
//expression to check for 3 ordered point
int val = (b.y - a.y) * (c.x - b.x) - (b.x - a.x) * (c.y - b.y);
// check for collinear
if (val == 0) return 0;
// check for clock or counterclock wise
return (val > 0)? 1: 2;
}
}
class Point{
int x, y;
Point(int x,int y){
this.x=x;
this.y=y;
}
}
輸出
The given 3 points form : Linear
在這篇文章中,我們探討了如何使用Java程式語言檢查3個有序點的方向。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP