Muldawg2020 - 4 months ago 26

Java Question

So I'm trying to compare the row/col location of 2 elements to see if they're adjacent. After a lot of searching I could not find what I was looking for on similar questions on SO.

Anyways, my main question is just in regards to the syntax on one of my lines of code. So here's what I have:

`private boolean adjacent(int row, int col)`

{

boolean adjacent = true;

Dot d2 = gameArray[row][col];

Descriptor D2 = new Descriptor (row, col, d2);

Descriptor D1 = list.get(list.size()-1);

if (D1.row() == D2.row() && D1.col() == D2.col() +1) {

adjacent = true;

}

return adjacent;

}

Basically what I'm looking at is the

`if`

`col`

`|1|`

How would I implement that to the

`== D2.col()`

`if`

Thanks

Answer

One way to do it is:

```
if (Math.abs(D1.row() - D2.row()) + Math.abs(D1.col() - D2.col()) == 1)
```

The sum of two non-negative integers is 1 if and only if exactly one of them is equal to 1 and the other is equal to zero, precisely what you want.

EDIT: now that I read your question more carefully, I realize that you do not consider two elements adjacent if they are in the same column in adjacent rows. Then the statement is even simpler:

```
if (D1.row() == D2.row() && Math.abs(D1.col() - D2.col()) == 1)
```