P D Tan - 10 months ago 181

Java Question

I have a Connect Four "board" which is a 6*7 2D char array populated with either spaces, X or O. The win condition is met when there are either four Xs or four Os in a row vertically, horizontally or diagonally. I've managed to get the win conditions checked successfully for vertical and horizontal, where the winning char is returned by some methods as below:

`private char CheckVerticalWinner(char[][] currentBoard) {`

// check vertical (move down one row, same column)

char vWinner = ' ';

for (int col=0; col<7; col++) {

int vCount = 0;

for (int row=0; row<5; row++) {

if (currentBoard[row][col]!=' ' &&

currentBoard[row][col] == currentBoard[row+1][col]) {

vCount++;

System.out.println("VERT "+vCount); //test

} else {

vCount = 1;

}

if (vCount>=4) {

vWinner = currentBoard[row][col];

}

}

}

return vWinner;

}

private char CheckHorizontalWinner(char[][] currentBoard) {

// check horizontal (move across one column, same row)

char hWinner = ' ';

for (int row=0; row<6; row++) {

int hCount = 0;

for (int col=0; col<6; col++) {

if (currentBoard[row][col]!=' ' &&

currentBoard[row][col] == currentBoard[row][col+1]) {

hCount++;

System.out.println("HORIZ "+hCount); //test

} else {

hCount = 1;

}

if (hCount>= 4) {

hWinner = currentBoard[row][col];

}

}

}

return hWinner;

}

I'm just stuck on how to check for diagonal wins, without throwing an ArrayIndexOutOfBoundsException. I know I need to iterate through the 2D array twice, once for forward diagonals and once for backward diagonals

Diagonals to be checked diagram

Basically, how would I fill in this method to return a winning char?

`private char CheckDiagonalWinner(char[][] currentBoard) {`

// some iteration here

return dWinner;

}

Any help would be much appreciated!

Answer

The simplest algorithm probably is:

```
for every direction
for every coordinate
check whether the next 3 elements in this direction exist and are the same
```

in code:

```
final int maxx = 7;
final int maxy = 6;
char winner(char[][] board) {
int[][] directions = {{1,0}, {1,-1}, {1,1}, {0,1}};
for (int[] d : directions) {
int dx = d[0];
int dy = d[1];
for (int x = 0; x < maxx; x++) {
for (int y = 0; y < maxy; y++) {
int lastx = x + 3*dx;
int lasty = y + 3*dy;
if (0 <= lastx && lastx < maxx && 0 <= lasty && lasty < maxy) {
char w = board[x][y];
if (w != ' ' && w == board[x+dx][y+dy]
&& w == board[x+2*dx][y+2*dy]
&& w == board[lastx][lasty]) {
return w;
}
}
}
}
}
return ' '; // no winner
}
```

Source (Stackoverflow)