CS1020 Transformation Lab 1 Ex 1

Link to the question – Transformation Lab 1 Ex 1

import java.util.*;

class Matrix {
	int size;
	int matrix[][];
	public Matrix() {}
	public Matrix(int size) {
		this.size = size;
		this.matrix = new int[size][size];
	}
}

class Transformation {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int sizeOfArray = sc.nextInt();
		if(sizeOfArray >= 1 || sizeOfArray <= 100)
		{
			Matrix m = new Matrix(sizeOfArray);
			for(int i = 0; i < sizeOfArray; i++)
			{
				for(int j = 0; j < sizeOfArray; j++)
				{
					m.matrix[i][j] = sc.nextInt();
				}
			}
			int numberOfOperation = sc.nextInt();
			for(int i = 0; i < numberOfOperation; i++)
			{
				String operationType = sc.next();
				String direction = sc.next();
				if(operationType.equals("Rotate"))
				{
					int angle = Integer.parseInt(direction);
					m = rotate(m, angle);
				}
				else
				{
					m = reflect(m, direction);
				}
			}
			for(int i = 0; i < sizeOfArray; i++)
			{
				for(int j = 0; j < sizeOfArray; j++)
				{
					System.out.print(m.matrix[i][j]);
					if(j != (sizeOfArray-1))
					{
						System.out.print(" ");
					}
				}
				System.out.println();
			}
		}
		else
		{
			return;
		}
	}

	static Matrix rotate(Matrix m, int angle)
	{
		Matrix temp = m;
		int numberOfTimesToRotate = angle/90;
		for(int k = 0; k < numberOfTimesToRotate; k++)
		{
			Matrix temp2 = new Matrix(m.size);
			for(int i = 0; i < m.size; i++)
			{
				for(int j = 0; j < m.size; j++)
				{
					temp2.matrix[i][j] = temp.matrix[m.size-j-1][i];
				}
			}
			temp = temp2;
		}
		return temp;
	}

	static Matrix reflect(Matrix m, String directionToReflect)
	{
		Matrix temp = new Matrix(m.size);
		if(directionToReflect.equals("y"))
		{
			for(int i = 0; i < m.size; i++)
			{
				for(int j = 0; j < m.size; j++)
				{
					temp.matrix[i][m.size-j-1] = m.matrix[i][j];
				}
			}
		}
		else if(directionToReflect.equals("x"))
		{
			for(int i = 0; i < m.size; i++)
			{
				for(int j = 0; j < m.size; j++)
				{
					temp.matrix[m.size-i-1][j] = m.matrix[i][j];
				}
			}
		}
		return temp;
	}
}
Advertisements
This entry was posted in NUS, SoC and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s