A Journey 2 Eternity

Archive for August 2012

/* 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;
}
char* StrStr(const char *str, const char *target) 
{
	char *cp = (char *) str;
	char *s1, *s2;

	if ( !*target ) {
		return ((char *)str);
	}

	while (*cp)
	{
		s1 = cp;
		s2 = (char *) target;

		while ( *s1 && *s2 && (*s1 == *s2) ) {
			++s1;
			++s2;
		}

		if (!*s2) {
			return cp;
		}

		++cp;
	}

	return NULL;
}
Tags: ,

Pages

Categories

August 2012
M T W T F S S
« Jul    
 12345
6789101112
13141516171819
20212223242526
2728293031  

Blog Stats

  • 27,261 hits