简体   繁体   中英

Easiest way to check integer is either +1 or -1 Java

I want to the difference between two integers is +1 or -1. I think my code below is very clumsy to write. Is there any shorter way to check if two integers are just 1 apart? This seems like a simple solution, but I have 2d array of coordinates I want to check if two coordinates in the direct vicinity (either north, east, west, or south) of each other are selected.

Yes they are standard coordinates as the top left corner is 0,0, and the bottom right is 7,7. Essentially if one coordinate is selected, I wanted to check if there exists another coordinate where x or y differs by (+-) one.

//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
}

The simplest way I can think of is:

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

Where n1 and n2 are numbers.

怎么样:

   Math.abs(difference)==1

您可以使用Math.abs评估差异:

boolean isDifferenceOne = Math.abs(x1 - x2) == 1 && Math.abs(y1 - y2) == 1

Since we don't care whether the difference between x1 and x2 is 1 or -1, we can use the absolute value:

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

This works because if x1 is less than x2 , then Math.abs(x1 - x2) = Math.abs(-1) = 1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM