Muldawg2020 Muldawg2020 - 1 month ago 8
Java Question

Comparing 2 elements in a 2D array

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
row. I want to keep it simple and check if the
col
location of element D2 is +/- 1. So I wanted to use absolute value, but not as an ArrayList method, just something simple like
|1|
or something.

How would I implement that to the
== D2.col()
part of the
if
statement?

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)