Search code examples
javaarraysperformancechessbitboard

Flip one dimensional array board representation about the x axis


I am in the midst of programming a chess AI, and have encountered an issue with my implementation of piece-square tables. Since I only want to have one piece-square table per side, I need a function to flip the one-dimensional array that holds the values about the x-axis. For instance, this array:

[ 2, 4, 5, 3, 5, 0, 1, 4, 2 ]

would be flipped to:

[ 1, 4, 2, 3, 5, 0, 2, 4, 5 ]

I achieved this for the 0x64 array using nested loops using the following method (note: the example was only 3x3, but the following function adjusts for 8x8); however, I was wondering if there was something more efficient since time is a concern.

public int[] gridFromPerspective(int[] grid){

    int[] flippedGrid = new int[64];

    for(int i = 7; i < 32; i += 8){
        for(int j = 0; j < 8; j++){
            flippedGrid[i-j] = grid[63-(i-j)];
            flippedGrid[63-(i-j)] = grid[i-j];
        }
    }
}

I know you can flip a bit board easily and efficiently using sq' = sq ^ 56, but am not certain how I can use this technique in the case of a one-dimensional array. Any advice will be appreciated.


Solution

  • The method you use does not in fact flip the board about the x-axis, but rather rotate the board in its entirety. In essence, grid[0] will always have the same value as flippedGrid[63]. If you want to view the board from the other players perspective, this is actually correct, you can however reduce your loops down to

    for (int i = 0; i < 64; i++) {
        flippedGrid[i] = grid[63-i];
    }
    

    This should provide a (very) small increase in performance.

    If you however actually want to flip the board about the x-axis, you can use System.arraycopyto gain a performance increase:

    for (int i = 0; i < 8; i++) {
        System.arraycopy(grid, 8*i, flippedGrid, 64 - 8*(i+1), 8);
    }
    

    That way, instead of copying single values, you let the JVM copy chunks of length 8 (a row) at once.

    Regardless what the method is supposed to do, you might also want to think about just keeping a flipped copy of your grid and mirroring the changes appropriately. That way, you eliminate the need to rotate the board, at the cost of higher memory usage (and being more difficult to code and/or maintain).