L
lovecreatesbea...
Hello experts,
I code an function to rotate a matrix by 90 degrees clockwise. The
matrix can be in any size provided its length equals to width. The one
minor limitation is that this requires an extra external macro
definition MTXROT_SIZE. Your comments are welcome on this code. Thank
you for your time.
/
*******************************************************************************
* Rotate an matrix of any size by 90 degrees colckwise if its length
equals to
* width, for example:
*******************************************************************************/
#define MTXROT_SIZE 5 /* length or width of the matrix */
void *mtxrot(void *mtx)
{
int (*p)[MTXROT_SIZE] = mtx;
const int INDMAX = MTXROT_SIZE - 1;
const int SCMAX = MTXROT_SIZE % 2 ? MTXROT_SIZE / 2 - 1 : INDMAX /
2;
int r, c, i;
for (r = 0; r <= INDMAX / 2; r++)
for (c = 0; c <= SCMAX; c++){
i = p[r][c];
p[r ][c ] = p[INDMAX - c][r ];
p[INDMAX - c][r ] = p[INDMAX - r][INDMAX - c];
p[INDMAX - r][INDMAX - c] = p[c ][INDMAX - r];
p[c ][INDMAX - r] = i;
}
return p;
}
for example, for a 5 x 5 matrix:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
21 16 11 6 1
22 17 12 7 2
23 18 13 8 3
24 19 14 9 4
25 20 15 10 5
for an 6 x 6 matrix:
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24
25 26 27 28 29 30
31 32 33 34 35 36
31 25 19 13 7 1
32 26 20 14 8 2
33 27 21 15 9 3
34 28 22 16 10 4
35 29 23 17 11 5
36 30 24 18 12 6
I code an function to rotate a matrix by 90 degrees clockwise. The
matrix can be in any size provided its length equals to width. The one
minor limitation is that this requires an extra external macro
definition MTXROT_SIZE. Your comments are welcome on this code. Thank
you for your time.
/
*******************************************************************************
* Rotate an matrix of any size by 90 degrees colckwise if its length
equals to
* width, for example:
*******************************************************************************/
#define MTXROT_SIZE 5 /* length or width of the matrix */
void *mtxrot(void *mtx)
{
int (*p)[MTXROT_SIZE] = mtx;
const int INDMAX = MTXROT_SIZE - 1;
const int SCMAX = MTXROT_SIZE % 2 ? MTXROT_SIZE / 2 - 1 : INDMAX /
2;
int r, c, i;
for (r = 0; r <= INDMAX / 2; r++)
for (c = 0; c <= SCMAX; c++){
i = p[r][c];
p[r ][c ] = p[INDMAX - c][r ];
p[INDMAX - c][r ] = p[INDMAX - r][INDMAX - c];
p[INDMAX - r][INDMAX - c] = p[c ][INDMAX - r];
p[c ][INDMAX - r] = i;
}
return p;
}
for example, for a 5 x 5 matrix:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
21 16 11 6 1
22 17 12 7 2
23 18 13 8 3
24 19 14 9 4
25 20 15 10 5
for an 6 x 6 matrix:
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24
25 26 27 28 29 30
31 32 33 34 35 36
31 25 19 13 7 1
32 26 20 14 8 2
33 27 21 15 9 3
34 28 22 16 10 4
35 29 23 17 11 5
36 30 24 18 12 6