I have a squared 2D array that I would like to rotate clockwise and counter clockwise.
I was following this answer here for rotating to the right:
Rotating a 2D pixel array by 90 degrees
The code I developed:
void rotateRight()
{
for (int i = 0; i < m_width; i += 1) {
for (int j = i + 1; j < m_height; j += 1) {
std::swap(get(i, j), get(j, i));
}
}
}
However, the array did not rotate. I have a 10x10 array with 5's, and on the top-left corner is a 7. I expected the 7 to go to the top-right corner after rotating, but it's still at the top-left corner.
The member function get() is my own, which just returns a reference to a cell.
T& get(const int x, const int y)
{
return m_array[y * m_width + x];
}
How can I get this to rotate? Does a new array have to be made? Would appreciate the help. Thanks!
Update:
Latest attempt. Okay, so the '7' rotated to the right finally from the top-left corner to the top-right corner. But when rotateRight() is called again, it fails. My 7 on the top-right corner is gone and no longer found. Looking into it.
for (int i = 0; i < m_width; i += 1) {
for (int j = i + 1; j < m_height; j += 1) {
get(j, i) = get(i, j);
}
}
for (int i = 0; i < m_height; i++) {
for (int j = 0, k = m_height - 1; j<k; j++, k--) {
std::swap(get(j, i), get(k, i));
}
}
Output:
Original:
700
000
000
Rotation #1:
J: 1, I: 0
J: 2, I: 0
J: 2, I: 1
J: 0, I: 0, K: 2
Value: 7 J: 0 K: 2
J: 0, I: 1, K: 2
Value: 0 J: 0 K: 2
J: 0, I: 2, K: 2
Value: 0 J: 0 K: 2
007
000
000
Rotation #2:
J: 1, I: 0
J: 2, I: 0
J: 2, I: 1
J: 0, I: 0, K: 2
Value: 0 J: 0 K: 2
J: 0, I: 1, K: 2
Value: 0 J: 0 K: 2
J: 0, I: 2, K: 2
Value: 0 J: 0 K: 2
000
000
000
Final code
// Rotates a squared array clockwise.
void rotateRight()
{
T temp;
int halfwidth_floor = m_width / 2;
int halfwidth_ceil = (m_width + 1) / 2;
for (int j = 0; j < halfwidth_floor; j += 1) {
for (int i = 0; i < halfwidth_ceil; i += 1) {
std::swap(temp, get(i, j));
std::swap(get(i, j), get(j, m_width - i - 1));
std::swap(get(j, m_width - i - 1), get(m_width - i - 1, m_width - j - 1));
std::swap(get(m_width - i - 1, m_width - j - 1), get(m_width - j - 1, i));
std::swap(get(m_width - j - 1, i), temp);
}
}
}
// Rotates a squared array counter-clockwise.
void rotateLeft()
{
T temp;
int n = m_width;
for (int i = 0; i < n / 2; i++) {
for (int j = i; j < n - i - 1; j++) {
std::swap(temp, get(i, j));
std::swap(get(i, j), get(n - j - 1, i));
std::swap(get(n - j - 1, i), get(n - i - 1, n - j - 1));
std::swap(get(n - i - 1, n - j - 1), get(j, n - i - 1));
std::swap(get(j, n - i - 1), temp);
}
}
}