A Journey 2 Eternity

Archive for the ‘C++11’ Category

/* Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes,
 * write a method to rotate the image by 90 degrees.
 */

#include <iostream>
#include <array>
#include <assert.h>

using  namespace std;

template <class T, size_t COL, size_t ROW>
struct Matrix
{
	std::array<std::array<T, COL>, ROW> data;
};

template <class T>
void Rotate(T &t, size_t rows, size_t columns)
{
	assert (rows == columns);

	int n = rows;
	for (int layer = 0; layer < n/2; ++layer) {
		int first = layer;
		int last = n - 1 - layer;
		for (int i = first; i < last; ++i) {
			int offset = i - first;

			// save top
			int top = t[first][i];

			// left -> top
			t[first][i] = t[last - offset][first];
			// bottom -> left
			t[last - offset][first] = t[last][last - offset];
			// right -> bottom
			t[last][last - offset] = t[i][last];
			// top -> right
			t[i][last] = top;
		}
	}
}

template <class T>
void PrintMatrix(T &t, size_t rows, size_t columns)
{
	for(size_t i = 0;i < rows; ++i) {
		for(size_t j = 0;j < columns; ++j) {
			cout << t[i][j] << "\t";
		}
		cout << endl;
	}
	cout << endl;
}

int main()
{
	Matrix<int, 4, 4> matrix;

	cout << endl << "Before Rotate:" << endl;
	int imagebit = 0;
	for (int i = 0; i < 4; i++) {
		for (int j = 0; j < 4; j++) {
			matrix.data[i][j] = imagebit++;
		}
	}
	PrintMatrix(matrix.data, 4, 4);

	cout << "After Rotate:" << endl;
	Rotate(matrix.data, 4, 4);
	PrintMatrix(matrix.data, 4, 4);

	return 0;
}

Pages

Categories

April 2017
M T W T F S S
« Aug    
 12
3456789
10111213141516
17181920212223
24252627282930

Blog Stats

  • 26,880 hits