2014-02-20 39 views
0

我想兩個整數之間的差異是+1或-1。我認爲我的代碼非常笨拙。有沒有更簡單的方法來檢查兩個整數是否相距1?這似乎是一個簡單的解決方案,但我有2d座標數組我想檢查是否選擇了彼此直接鄰近(北,東,西或南)的兩個座標最簡單的方法來檢查整數是+1或-1 Java

是的,它們是標準座標,左上角是0,0,右下角是7,7。本質上,如果選擇了一個座標,我想檢查是否存在另一個座標,其中x或y相差(+ - )。

//Since it's a 2d array, I am doing a nested loop. But comparison is below 

int x1 = range(0,8); //all ints are range from 0 to 7 
int y1 = range(0,8); //represent the current indices from the loop 

int x2 = ...; //x2 represents the x index value of the previous loop 
int y2 = ...; //y2 represents the y index value of the previous loop 

if(x1+1 == x2){ 
    Found an existing X coord just larger by one 
}else if (x1-1 == x2){ 
    Found an existing X coord smaller, and differ by one 
}else if(y1+1 == y2){ 
    Found an existing Y coord just 1 larger 
}else if(y-1 == y2){ 
    Found an existing Y coord just 1 smaller 
} 
+0

那麼point1 =(1,1)和point2 =(2,2)的情況如何呢? – turbo

回答

1

因爲我們不在乎X1和X2之間的差值是1或-1,我們可以使用絕對值:

if (Math.abs(x1 - x2) == 1){ 
    // x coordinates differ by 1 
} else if (Math.abs(y1 - y2) == 1){ 
    // y coordinates differ by 1 
} 

這是可行的,因爲如果x1小於x2,然後Math.abs(x1 - x2) = Math.abs(-1) = 1

1

我能想到的最簡單的方法是:

boolean differenceOfOne = Math.abs(n1 - n2) == 1; 

n1n2是數字。

1

如何:

Math.abs(difference)==1 
1

您可以使用Math.abs評估的區別:

boolean isDifferenceOne = Math.abs(x1 - x2) == 1 && Math.abs(y1 - y2) == 1 
相關問題