Search code examples
javastaticgridcharsymmetry

Checking symmetry in a grid with java


I need help with a game I'm doing:

The game is the following, There are two players, 'B' and 'N'. There is a grid of characters. Both players take turn to place a char (B or N depending on who they are) on the grid. Every time they place a char, I have to check whether there a symmetry is occuring. For example. There are differents types of symmetries. Horizontal and Vertical in every 2*2, 3*3 and 4*4 squares that contains the char that was just placed here. In the case of the 3*3 symmetry, the middle row or column does not take place in the symmetry.

I have done everything until now except the symmetries. I'm having some difficutly at doing them. I have an idea on how to do them but individually. Does any of you know how I could do the symmetries in one method only?


Solution

  • The java code for something similar to what you described for an n by n sized grid would go something like:

    boolean isHorizontallySymmetrical(char[][] grid, int n){
        int across = n / 2;
    
        for(int i = 0; i < n; i++){
            int right = 0
            for(int left = 0; left < across; left++){
                right = n - left - 1;
    
                if(grid[i][left] != grid[i][right]){
                    return false;
                }
            }
        }
    
        return true;
    }
    

    A similar sort of thing would be needed for a vertical symmetry function.