Check the diagonal of a 2d array?

I am trying to search on a 3x3 2d diagonal like: enter image description here

I want to check if all boxes in the diagonal have the same value. This is how I try to do it:

thisOne = board[0][2];    //set to 'X'
    for(i = 0; i<3; i++) {
        for(j = 3; j>0; j--){
            if(board[i][j-1] != thisOne) {
                thisOne= '\0';
            }
        }
    }
//since all boxes were 'X', thisOne is still set to 'X'
if(thisOne != '\0') {
    winner = thisOne;
    printf("vinnare pΓ₯ nΓΆrdΓΆst\n");
}

      

So after running this code it winner

should be "X" if all fields are X. But the code doesn't do that, why?

+3


source to share


6 answers


You only need to check diagonal cells, not check all cells.



+1


source


You don't break / exit the check loop when the first non-matching char is retrieved.

Also, your nested is not what you assume for you: inner one loops across all columns of each row, but you only want the diagonal values ​​...



You can easily create a simple while

int i=0;
int j=2;
while ((i<3) && (j>=0) && (board[i][j] == thisOne))
{
   i++;
   j--;
}

// if i<3 the diagonal is not full of thisOne char
if ( i < 3)
{
}

      

+1


source


As @BLUEPIXY said, the problem is that the loop is j

nested inside the loop i

. Therefore, for each iteration in the loop, the i

loop j

is executed three times along each column, and not just along the small diagonal. There are several ways to fix this, although the most optimal way would be to use only one single loop and only one variable i

.

for(i=0;i<3;i++) {
    if(board[i][2-i]!=thisOne) {
        thisOne='\0'
        break;
    }
}

      

+1


source


To achieve your goal, you just need to shrink the X iterator X and the Y iterator while walking through your array.

Here's a simple example:

#include <stdio.h>
#include <stdlib.h>

int     main(void)
{
  int   arr[3][3];
  int   it_y;
  int   it_x;

  it_y = 0;
  it_x = 2;
  arr[0][0] = 0;
  arr[0][1] = 1;
  arr[0][2] = 2;
  arr[1][0] = 3;
  arr[1][1] = 4;
  arr[1][2] = 5;
  arr[2][0] = 6;
  arr[2][1] = 7;
  arr[2][2] = 8;
  while (it_x < 3 && it_x >= 0)
    {
      printf("[%d][%d]: '%d'\n", it_y, it_x, arr[it_y][it_x]);
      --it_x;
      ++it_y;
    }
  return EXIT_SUCCESS;
}

      

0


source


You can do for example

for(int row=0,col=2; row<3; row++,col--)
{
    if(board[row][col] != thisOne) 
    {
            thisOne= '\0';
    }
}

      

0


source


You can only check for diagonal elements like

for(i = 0, j = 3-1; i < 3; i++, j--) { 
    if(board[i][j] != thisOne) { 
       thisOne = '\0'; 
    } 
 }

      

0


source







All Articles