Search code examples
c++arraysloops2ddiagonal

looping through a 2D array (diagonal) c++


So I initialized an array as array[8][8] let's suppose that I'm at point (row, column) and for example, it is row 4 column 4 and I want to loop through every diagonal direction (southeast, southwest, northeast, northwest)

8*8 Array

so I wrote 4 different functions to check each direction alone, and here is an example for Northeast

for(int i = 0; i < 8; i++)
    for(int j = 0; j < 8; j++)
        if(array[i - 1][j+1] == 'x')
        {
           count = count + 1; 
        }

is there is a way to loop in all diagonal directions at the same time? another problem is what about getting out of bounds, like if the point is (7,7), then there will be no value in northeast because it will exceed the array bounds array[6][8], and that is out of array bounds. How can I deal with this problem? or does the compiler return an error when it happens?


Solution

  • You can of course check in each direction, e.g.

    for(int i = 0; i < 8; i++) {
        for(int j = 0; j < 8; j++) {
            if (check_north_east(array, i, j))
                ++count;
    
            if (check_north_west(array, i, j))
                ++count;
    
            if (check_south_east(array, i, j))
                ++count;
    
            if (check_south_west(array, i, j))
                ++count;
        }
    }
    

    The compiler will happily go beyond the array bounds. So you must make sure, the code won't do it, and check yourself

    const int NROWS = 8, NCOLS = 8;
    bool check_north_east(char array[][NCOLS], int row, int col)
    {
        if (row <= 0 || col >= NCOLS - 1)
            return false;
    
        return array[row - 1][col + 1] == 'x';
    }