Efficiently crushing an array
in
Programming Questions
•
1 years ago
(I'm not sure if there is a more technical term than crushing). I am making a chess environment and I am trying to speed optimize the generation of possible moves an AI could make. Right now I have a function that correctly finds every possible move the pieces could make on any given turn. Then next step is removing the moves that leave the King in check from the list (it is considered an illegal move to leave your King in check). For example:
int numPossibleMoves = 0;
getNumberOfPossibleMoves(); // Now numPossibleMoves is set to the correct number
int[] possibleMoves = new int[numPossibleMoves];
boolean[] illegalMove = new boolean[numPossibleMoves];
for (int i = 0; i < numPossibleMoves; i++) {
make the move
if (the move leaves the King in check) illegalMove[i] = true;
undo the move I tested
}
int keptMoves = 0;
int[] movesToKeep = new int[numPossibleMoves];
for (int i = 0; i < numPossibleMoves; i++) {
if (illegalMove[i] == false) {
movesToKeep[keptMoves] = possibleMoves[i];
keptMoves++;
}
}
for (int i = 0; i < keptMoves; i++) {
possibleMoves[i] = keptMoves[i];
}
numPossibleMoves = keptMoves;
And now my list of possible moves only has the moves that are legal up to the variable marker. The rest of the array beyond the marker is ignored. The problem is that this seems like a very long winded and slow method of removing illegal moves. There must be a better way of removing illegal moves that is faster, any ideas?
1