Last active
November 4, 2025 11:51
-
-
Save juanfal/66dafa705d5fac43f1672315047d1d63 to your computer and use it in GitHub Desktop.
rotate matrix
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // t14e12.rotate.cpp | |
| // juanfc 2025-11-04 | |
| // https://gist.github.com/juanfal/66dafa705d5fac43f1672315047d1d63 | |
| #include <iostream> | |
| #include <iomanip> | |
| #include <array> | |
| using namespace std; | |
| const int MAX = 5; | |
| typedef array<array<int,MAX>,MAX> TSqMat; | |
| int main() | |
| { | |
| void print(TSqMat); | |
| void clockwise(TSqMat& m); | |
| void counterClockwise(TSqMat& m); | |
| TSqMat m = {{ | |
| {{ 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}} | |
| }}; | |
| TSqMat copy = m; | |
| cout << "orig:" << endl; | |
| print(m); | |
| clockwise(m); | |
| cout << "orig clockwise:" << endl; | |
| print(m); | |
| m = copy; | |
| counterClockwise(m); | |
| cout << "orig counterClockwise:" << endl; | |
| print(m); | |
| clockwise(m); | |
| cout << "orig counterClockwise + clockwise:" << endl; | |
| print(m); | |
| return 0; | |
| } | |
| void counterClockwise(TSqMat& m) | |
| { | |
| void transpose(TSqMat&); | |
| void invertCols(TSqMat&); | |
| transpose(m); | |
| invertCols(m); | |
| } | |
| void clockwise(TSqMat& m) | |
| { | |
| void transpose(TSqMat&); | |
| void invertRows(TSqMat&); | |
| transpose(m); | |
| invertRows(m); | |
| } | |
| void transpose(TSqMat& m) | |
| { | |
| void swap(int&, int&); | |
| for (int row = 0; row < MAX; ++row) | |
| for (int col = row+1; col < MAX; ++col) | |
| swap(m[row][col], m[col][row]); | |
| } | |
| void invertCols(TSqMat& m) | |
| { | |
| void swap(int&, int&); | |
| for (int row = 0; row < MAX/2; ++row) | |
| for (int col = 0; col < MAX; ++col) | |
| swap(m[row][col], m[MAX-1-row][col]); | |
| } | |
| void invertRows(TSqMat& m) | |
| { | |
| void swap(int&, int&); | |
| for (int row = 0; row < MAX; ++row) | |
| for (int col = 0; col < MAX/2; ++col) | |
| swap(m[row][col], m[row][MAX-1-col]); | |
| } | |
| void print(TSqMat m) | |
| { | |
| for (int i = 0; i < MAX; ++i) { | |
| for (int j = 0; j < MAX; ++j) | |
| cout << setw(4) << m[i][j]; | |
| cout << endl; | |
| } | |
| } | |
| void swap(int& a, int& b) | |
| { | |
| int t=a;a=b;b=t; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment