So, I am doing a board game from 19 to 19. This is basically compound 5, called Gomoku.
I want to make an efficient algorithm to find if there are "n" pieces in a string. Data is stored as a 19x19 2D array. But for the sake of the question, let's say, 6x6.
0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1
These are two examples of "5" from 1 line. How can I check HORIZONTAL, VERTICAL and both DIAGONALS?
Here is my inefficient code:
private boolean firstDiagonalCheck(int x, int y, int num) { int count = 1; int check = 0; boolean rflag = true; boolean lflag = true; int pos = 1; check = turnHuman + 1; while (rflag) { if (x + pos >= 19 || y + pos >= 19) { rflag = false; break; } if (gb.getBoard()[x + pos][y + pos] == check) { count++; pos++; } else { rflag = false; } } pos = 1; while (lflag) { if (x - pos < 0 || y - pos < 0) { lflag = false; break; } if (gb.getBoard()[x - pos][y - pos] == check) { count++; pos++; } else { lflag = false; } } if (count == num) { return true; } return false; }
This is only one method for the first diagonal. There are 3 more.
How can I make it more efficient and check all 4 directions?
EDIT ####################
What my code does: - Get the position of the part (x, y) - Check both sides (up and down, if vertically), and count how many are in the row - If the number of matches matches the desired one, ("num"), then return true otherwise return false.
It would be better if I checked the WHOLE board each time to see if there were any pieces in a row?
source share