Created
September 30, 2015 17:26
-
-
Save goldsborough/c41a5e4c56048adad479 to your computer and use it in GitHub Desktop.
Matrix rotation
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
template<std::size_t N> | |
void rotate_out_of_place(std::size_t (&matrix) [N][N]) | |
{ | |
std::size_t copy [N][N]; | |
for (std::size_t i = 0, end = N/2; i < end; ++i) | |
{ | |
for (std::size_t j = 0; j < N; ++j) | |
{ | |
copy[i][j] = matrix[j][N - 1]; | |
copy[N - 1 - i][j] = matrix[j][i]; | |
copy[j][i] = matrix[i][N - 1 - j]; | |
copy[j][N - 1 - i] = matrix[N - 1 - i][N - 1 - j]; | |
} | |
} | |
if (N % 2) copy[N/2][N/2] = matrix[N/2][N/2]; | |
for (std::size_t i = 0; i < N; ++i) | |
{ | |
for (std::size_t j = 0; j < N; ++j) | |
{ | |
matrix[i][j] = copy[i][j]; | |
} | |
} | |
} | |
template<std::size_t N> | |
void rotate(std::size_t (&matrix) [N][N], std::size_t i, std::size_t j) | |
{ | |
std::size_t temp = matrix[i][j]; | |
matrix[i][j] = matrix[j][N - 1]; | |
matrix[j][N - 1 - i] = matrix[N - 1 - i][N - 1 - j]; | |
matrix[N - 1 - i][N - 1 - j] = matrix[N - 1 - j][i]; | |
matrix[N - 1 - j][i] = temp; | |
} | |
template<std::size_t N> | |
void rotate_in_place(std::size_t (&matrix) [N][N]) | |
{ | |
for (std::size_t i = 0, i_end = std::ceil(N/2.0); i < i_end; ++i) | |
{ | |
for (std::size_t j = i, j_end = N - i; j < j_end; ++j) | |
{ | |
rotate(matrix, i, j); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment