我有以下代碼,並且我可以看到值之間有連接。然而,我可以不把我的腦袋集中在一起,並找出如何用一些加減模式刪除開關語句。會真正appriciate一些幫助,讓這種方法更順暢。我有一個腦凍結,幫助我使這種方法高效:>
的標題變量或者是0,1,2或3。
public static int getRotation(Point currentPoint, Point nextPoint, int heading) {
int rotation = -1;
if(currentPoint.getX() < nextPoint.getX()) /* DRIVE WEST */ {
switch(heading) {
case 0: rotation = 1; break;
case 1: rotation = 0; break;
case 2: rotation = 3; break;
case 3: rotation = 2; break;
}
} else if(currentPoint.getX() > nextPoint.getX()) /* DRIVE EAST */ {
switch(heading) {
case 0: rotation = 3; break;
case 1: rotation = 2; break;
case 2: rotation = 1; break;
case 3: rotation = 0; break;
}
} else if(currentPoint.getY() < nextPoint.getY()) /* DRIVE NORTH */ {
switch(heading) {
case 0: rotation = 0; break;
case 1: rotation = 3; break;
case 2: rotation = 2; break;
case 3: rotation = 1; break;
}
} else if(currentPoint.getY() > nextPoint.getY()) /* DRIVE SOUTH */ {
switch(heading) {
case 0: rotation = 2; break;
case 1: rotation = 1; break;
case 2: rotation = 0; break;
case 3: rotation = 3; break;
}
}
return rotation;
}
編輯:我沒有忘記提及NextPoint公司只能是+ -x或相比當前點年。如果currentPoint是(0,0)newPoint必須是(-1,0),(1,0),(0,-1)或(0,1)。
你確實意識到你的算法更喜歡在南北向之前驅動西部和東部? – orlp 2011-04-04 15:02:18
我甚至不確定這是否正確。在效率之前我會擔心這一點。你如何移動NW或SE? – duffymo 2011-04-04 15:07:41
使用枚舉。這就是他們在那裏。 http://download.oracle.com/javase/tutorial/java/javaOO/enum.html – I82Much 2011-04-04 15:08:21