Как уменьшить количество if в коде?
Суть кода в том чтобы он высчитывал количество соседей у клетки по координатам.
Есть список с координатами живых клеток, код смотрит есть ли у данной клетки живые соседи.
public Integer getNeighbourCount(int x, int y) {
int counter = 0;
for (ArrayList<Integer> coordinate : coordinates) {
if (coordinate.get(0) == x && coordinate.get(1) == y + 1) {
counter++;
} else if (coordinate.get(0) == x + 1 && coordinate.get(1) == y) {
counter++;
} else if (coordinate.get(0) == x && coordinate.get(1) == y - 1) {
counter++;
} else if (coordinate.get(0) == x - 1 && coordinate.get(1) == y) {
counter++;
} else if (coordinate.get(0) == x + 1 && coordinate.get(1) == y + 1) {
counter++;
} else if (coordinate.get(0) == x - 1 && coordinate.get(1) == y - 1) {
counter++;
} else if (coordinate.get(0) == x - 1 && coordinate.get(1) == y + 1) {
counter++;
} else if (coordinate.get(0) == x + 1 && coordinate.get(1) == y - 1) {
counter++;
}
}
return counter;
}
Нужно уменьшить количество if.
Ответы (2 шт):
Автор решения: Roman Konoval
→ Ссылка
Можно так:
int cx = coordinate.get(0);
int cy = coordinate.get(1);
if (cx >= x-1 && cx <= x+1 && cy >= y-1 && cy <= y+1) {
counter++;
}
Автор решения: tym32167
→ Ссылка
Как вариант
public Integer getNeighbourCount(int x, int y) {
int counter = 0;
for (ArrayList<Integer> coordinate : coordinates) {
int cx = coordinate.get(0);
int cy = coordinate.get(1);
if (cx == x && cy == y) continue;
if (Math.abs(cx - x) <= 1 && Math.abs(cy - y) <= 1) counter++;
}
return counter;
}