How to loop a matrix, does the number on the diagonal have high priority?

I am working on a project that needs to find a specific number in a two dimensional array (matrix). The visiting order of the matrix order is the same (4 * 4 matrix). I am now at position 0. Equivalently, I want to see the matrix element diagonally first.

0  2  7  14
3  1  5  12
8  6  4  10
15 13 11 9

      

Also, how to break two nesting loops in C ++ without using a goto statement.

+3


source to share


3 answers


The following code will intersect a square matrix of any size with priority on the diagonal

#define SIZE 4

static int test[SIZE][SIZE] =
{
    {   0,    2,    7,    14  },
    {   3,    1,    5,    12  },
    {   8,    6,    4,    10  },
    {  15,   13,   11,     9  }
};

int main( void )
{
   int diagonal, delta;

   for ( diagonal = 0; diagonal < SIZE; diagonal++ )
   {
       cout << test[diagonal][diagonal] << endl;

       for ( delta = 1; delta <= diagonal; delta++ )
       {
           cout << test[diagonal-delta][diagonal] << endl;
           cout << test[diagonal][diagonal-delta] << endl;
       }
   }
}

      



Here's one way to break out of the nested loop without goto

done = false;
for ( i = 0; i < 10; i++ )
{
    for ( j = 0; j < 10; j++ )
    {
        if ( some_condition_is_met )
        {
            done = true;
            break;
        }
    }
    if ( done )
        break;
}

      

+3


source


Use a different array with array indices (since the size of your array is probably constant), for example, if you stored the first array in one C ++ sized array, then

int actual_arr[16];
int indices[16] = {0, 5, 1, 4, 10, 6, 9, 2, 8, 15, 11, 14, 7, 13, 3, 12 };

      

So, you can write a loop:

for (int i = 0; i  < 16; ++i)
{
  actual_arr[indices[i]]++;
}

      



Thus, each field in the indices is the actual_arr index that will be visited at that moment. You can do this with a 2D view as well, if required. Just swap int indices[16]

with std::pair<int, int> indices[16]

and you should be good to go.

Especially if you have a fixed size array and visit it many times, this is a good solution since it doesn't involve looping.

Btw. As a side element, mathematically speaking, an array of indices will be called a permutation and can be an operation in a transition group .

+3


source


To move to the item on the right, you increment the line.
To move to the element on the left, you shrink the line.
To get to the item below, you increment the column.
To get to the item above, you will shrink the column.

Now, to move diagonally, watch the row and columns change and apply a combination of the above.

+1


source







All Articles