user4154395
user4154395

Reputation:

Searching diagonal in a 2d array

I am trying to search diagonally in a 2D array for a connect four game. I thought I had it figured out, but apparently I am wrong. The first set of for loops work fine, searching right to left, diagonally. The second set of for loops, do not work. I thought all i had to do was switch some positive signs to negative and it work. Eventually, I was able to get it to work partially, by changing the GRID_HEIGHT-1...BUT, I keep getting bound errors. Any help at this point would be greatly appreciated. Also, the grid for the 2d array is 5x4. So its really connect 3.

    for (int y = 0; y <= GRID_HEIGHT-3; y++) {
        for (int x = 0; x <= GRID_WIDTH-3; x++) {
            if (    
                    state[y][x] != Player.NONE && 
                    state[y][x] == state[y+1][x+1] &&
                    state[y+1][x+1] == state[y+2][x+2]
                    ) return state[y][x];
        }
    }
    for (int y = 0; y <= GRID_HEIGHT-3; y++) {
        for (int x = 0; x <= GRID_WIDTH-3; x++) {
            if (    
                    state[y][x] != Player.NONE && 
                    state[y][x] == state[y-1][x-1] &&
                    state[y-1][x-1] == state[y-1][x-2]
                    ) return state[y][x];
        }
    }


    return Player.NONE;

}

Upvotes: 0

Views: 698

Answers (2)

Kevin
Kevin

Reputation: 91

For the second set of loops, you are subtracting from the indexes, which means that the index can go below zero. You need the loop to start above zero.

for (int y = 2; y < GRID_HEIGHT; y++) {
    for (int x = 2; x < GRID_WIDTH; x++) {
        if (    
                state[y][x] != Player.NONE && 
                state[y][x] == state[y-1][x-1] &&
                state[y-1][x-1] == state[y-2][x-2]
                ) return state[y][x];
    }
}

Also, generally you should be saying (x < GRID_HEIGHT) rather than (x <= GRID_HEIGHT-1) when applicable as the second is harder to read.

Upvotes: 2

Daniel
Daniel

Reputation: 6745

Instead of iterating from 0 to GRID_HEIGHT-3, iterate from GRID_HEIGHT downward to 3.

Upvotes: 0

Related Questions