Let's say you want to increment the cells around the position (x,y)
in a square matrix m
of size T
.
I've written the same code in a few languages. Here's the JS syntax version :
if (x>0) {
if (y>0) m[x-1][y-1]++;
m[x-1][y]++;
if (y<T-1) m[x-1][y+1]++;
}
if (y>0) m[x][y-1]++;
if (y<T-1) m[x][y+1]++;
if (x<T-1) {
if (y>0) m[x+1][y-1]++;
m[x+1][y]++;
if (y<T-1) m[x+1][y+1]++;
}
I don't like this kind of code, those tests look redundant. What bothers me is less the clarity of the code than the fact it has to do so many times the same checks.
But I don't see anything better. Am I just missing an obvious solution or is there nothing better with the branching toolset we have ? A slower code isn't acceptable as an answer, performance is the essence of the question.