Try this:
// x = number of columns
// s = index start
// a = index of a
// b = index of b
// if your index doesn't starts at 0
public static boolean isAdjacent(int x, int s, int a, int b) {
int ax = (a - s) % x, ay = (a - s) / x, bx = (b - s) % x, by = (b - s) / x;
return a != b && Math.abs(ax - bx) <= 1 && Math.abs(ay - by) <= 1;
}
// if your index starts at 0
public static boolean isAdjacent(int x, int a, int b) {
int ax = a % x, ay = a / x, bx = b % x, by = b / x;
return a != b && Math.abs(ax - bx) <= 1 && Math.abs(ay - by) <= 1;
}
Consider the gridview layout:
Two cells are adjacent if:
- their index (0~47) are different
- difference column number <= 1
- difference row number <= 1
Example:
isAdjacent(6, 18, 12) // true
isAdjacent(6, 18, 19) // true
isAdjacent(6, 18, 24) // true
isAdjacent(6, 18, 17) // false
isAdjacent(6, 18, 18) // false
Notes:
- If the first cell index is not 0, use first method with
s
argument - In this methods, diagonals are considered as adjacent :
Example:
isAdjacent(6, 18, 13) // true
isAdjacent(6, 18, 25) // true