How do we simplify this kind of code in Java? Something like macros in C?
Posted
by
Terry Li
on Stack Overflow
See other posts from Stack Overflow
or by Terry Li
Published on 2012-12-04T16:34:40Z
Indexed on
2012/12/04
17:04 UTC
Read the original article
Hit count: 235
public static boolean diagonals(char[][] b, int row, int col, int l) {
int counter = 1; // because we start from the current position
char charAtPosition = b[row][col];
int numRows = b.length;
int numCols = b[0].length;
int topleft = 0;
int topright = 0;
int bottomleft = 0;
int bottomright = 0;
for (int i=row-1,j=col-1;i>=0 && j>=0;i--,j--) {
if (b[i][j]==charAtPosition) {
topleft++;
} else {
break;
}
}
for (int i=row-1,j=col+1;i>=0 && j<=numCols;i--,j++) {
if (b[i][j]==charAtPosition) {
topright++;
} else {
break;
}
}
for (int i=row+1,j=col-1;i<=numRows && j>=0;i++,j--) {
if (b[i][j]==charAtPosition) {
bottomleft++;
} else {
break;
}
}
for (int i=row+1,j=col+1;i<=numRows && j<=numCols;i++,j++) {
if (b[i][j]==charAtPosition) {
bottomright++;
} else {
break;
}
}
return topleft + bottomright + 1 >= l || topright + bottomleft + 1 >= l; //in this case l is 5
}
After I was done posting the code above here, I couldn't help but wanted to simplify the code by merging the four pretty much the same loops into one method.
Here's the kind of method I want to have:
public int countSteps(char horizontal, char vertical) {
}
Two parameters horizontal
and vertical
can be either +
or -
to indicate the four directions to walk in. What I want to see if possible at all is i++;
is generalized to i horizontal horizontal;
when horizontal
taking the value of +
.
What I don't want to see is if
or switch
statements, for example:
public int countSteps(char horizontal, char vertical) {
if (horizontal == '+' && vertical == '-') {
for (int i=row-1,j=col+1;i>=0 && j<=numCols;i--,j++) {
if (b[i][j]==charAtPosition) {
topright++;
} else {
break;
}
}
} else if (horizontal == '+' && vertical == '+') {
for (int i=row+1,j=col+1;i>=0 && j<=numCols;i++,j++) {
if (b[i][j]==charAtPosition) {
topright++;
} else {
break;
}
}
} else if () {
} else {
}
}
Since it is as tedious as the original one. Note also that the comparing signs for the loop condition i>=0 && j<=numCols;
for example, >= && <=
have correspondence with the value combination of horizontal
and vertical
.
Sorry for my bad wording, please let me know if anything is not clear.
© Stack Overflow or respective owner