[英]How do I compare objects based on their location on a line
我正在嘗試編寫一個將與之進行比較的方法。
// If a and b lie on the same horizontal line,
// then a < b when a is to the left of b
// Otherwise, a < b when a is below b
我真的不知道該怎么做,通常我只是比較a> b是否返回+ ve int和-ve int如果小於或等於0。
根據您的建議我的解決方案.........
我使用吉姆·布萊克勒,拉爾夫和彼得·勞瑞的想法,提出了這個想法。 它對不起我有點困惑,沒有想到笛卡爾坐標,謝謝Aasmund Eldhuset,這是我最后的比較方法。
class Lexicographical實現Comparator {//需要重寫,因此...
//如果a和b位於同一水平線上,//那么a <b當a在b的左邊時// //否則,a <b當a在b以下時
public int compare(Point a,Point b){if(ay == by)// y軸相同(同一行){if(ax <bx)// b的左側(在x軸上)return -1; 否則返回1; ///在b的右邊}否則if(ay <by)// y軸不相同(在不相同的行下){return -1;
}
else
return 0;
}
}
你是說喜歡
class Point implements Comparable<Point> {
double x,y;
public int compareTo(Point b) {
// If a and b lie on the same horizontal line,
if (y == b.y)
// then a < b when a is to the left of b
return x < b.x ? -1 : x > b.x ? +1 : 0;
// Otherwise, a < b when a is below b
return y < b.y ? -1 : y > b.y ? +1 : 0;
}
}
對於a和b可以比較的類型,您將需要一個class屬性。 一旦開始更具體地思考,這很容易。
a和b的類型是什么?
if (a.y == b.y) {
return a.x < b.x;
} else {
return a.y < b.y;
}
從文本中,聽起來像a
和b
是笛卡爾坐標(每個都有x和y值)。 您是否有一個代表坐標的類? 如果不是,則應做一個,並且compare方法應采用該類的兩個實例,然后可以使用它們的x和y值確定它們是否在同一條水平線上,或者哪個在另一條水平線上。
在Java中實現compare方法的一種方法是Comparable接口
它只有一個方法int compareTo(T o)
。 此方法將此對象( 在其上調用了該方法的對象 )與指定的對象( b )進行比較。 當此對象小於,等於或大於指定的對象時,返回負整數,零或正整數。
假設對象屬於Pseudo類( 因為它只是偽代碼 ),那么compare方法應如下所示。
class Pseudo implements Comparable<Pseudo> {
@Override
int compareTo(Pseudo b) {
if (this and b lie on the same horizontal line) {
if (this is to the left of b) {
return -1;
} else {
return 1;
}
} else {
if (this is to the below of b) {
return -1;
} else {
return 1;
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.