-1

I have a matrix that stores pixels like this:

(0, 0, 255) (0, 255, 0) (255, 0, 0)
(0, 128, 0) (0, 255, 0) (0, 128, 0) 

with number of lines 2 and columns 3 [but actually 9 because of pixel r,g,b values] and i have to rotate them so i obtain:

(0, 128, 0) (0, 0, 255) 
(0, 255, 0) (0, 255, 0)
(0, 128, 0) (255, 0, 0)

with 3 lines and 2 columns. I also have a restriction: not allowed to use structures, only for-loops. Tried a variety of combinations but none of them is generally correct. Any help will be much appreciated.

adikinzor
  • 55
  • 1
  • 5

1 Answers1

1

You need to consider your matrix as being built from blocks. It contains BLOCK_MATRIX_M x BLOCK_MATRIX_N blocks. Each block contains BLOCK_M x BLOCK_N elements.

You need to rotate the matrix of blocks, but leave the blocks themselves unchanged:

#define BLOCK_MATRIX_M          2
#define BLOCK_MATRIX_N          3
#define BLOCK_M                 1
#define BLOCK_N                 3

#define MATRIX_M                (BLOCK_MATRIX_M * BLOCK_M)
#define MATRIX_N                (BLOCK_MATRIX_N * BLOCK_N)
#define ROTATED_MATRIX_M        (BLOCK_MATRIX_N * BLOCK_M)
#define ROTATED_MATRIX_N        (BLOCK_MATRIX_M * BLOCK_N)

int matrix[MATRIX_M][MATRIX_N] = {
    { 0, 0, 255, 0, 255, 0, 255, 0, 0 },
    { 0, 128, 0, 0, 255, 0, 0, 128, 0 }
};

int rotated_matrix[ROTATED_MATRIX_M][ROTATED_MATRIX_N];

// iterate over the blocks
for (int i = 0; i < BLOCK_MATRIX_M; i++) {
    for (int j = 0; j < BLOCK_MATRIX_N; j++) {
        int rotated_i = j;
        int rotated_j = BLOCK_MATRIX_M - i - 1;

        // iterate over the elements of a block
        for (int k = 0; k < BLOCK_M; k++) {
            for (int l = 0; l < BLOCK_N; l++) {
                int x = i * BLOCK_M + k;
                int y = j * BLOCK_N + l;
                int rotated_x = rotated_i * BLOCK_M + k;
                int rotated_y = rotated_j * BLOCK_N + l;

                rotated_matrix[rotated_x][rotated_y] = matrix[x][y];
            }
        }
    }
}