Home > database >  What is this java conditional doing?
What is this java conditional doing?

Time:03-05

I made a nine game puzzle in Java. The goal is get the numbers back in order. Game board below is stored in a 2d ArrayList. The game looks like:

2 5 1
3 6 7
4 8

A valid move would 7 or 8, in which case the blank space will swap with the selected number. 6 would not be valid, nor any numbers 1 - 6 in this state. The first way I coded my isValidMove function was a nightmare of nested switch & conditionals. I came across somebody else's code and it works perfectly for me. This is the code that replaced my nested mess:

int differenceX = Math.abs(empty1 - move1);
int differenceY = Math.abs(empty2 - move2);
if (differenceX <= 1 && differenceY <= 1 && !(differenceX == 1 && differenceY == 1))
{
    return true;
}
return false;

I understand what's happening until the && !(differenceX == 1 && differenceY == 1)). Checking the absolute value of the difference is 0 or 1 makes sense. It then seems to be also checking that the difference is not equal to 1. I presume this has something to do with ensuring a number like 6 isn't considered valid. Can someone please explain what is happening here? My brain hurts.

CodePudding user response:

Move the conditional out of the if and it might make more sens :

int differenceX = Math.abs(empty1 - move1);
int differenceY = Math.abs(empty2 - move2);

boolean isNearHorizontal = differenceX <= 1;
boolean isNearVertical = differenceY <= 1;
boolean isNearDiagonal = differenceX == 1 && differenceY == 1;

// is near horizontally and vertically and not diagonally !
if ( isNearHorizontal && isNearVertical && !isNearDiagonal )
{
    return true;
}
return false;

It does the same thing but might be easier to read to you.

By the way, Here is a trick many programmers catch on after a little while to further ease code reading

if (statement)
    return true
return false

is equivalent to

return statement
  • Related