How do we rotate a tetris piece counter clockwise? - java

I looked at the algorithm here for clockwise rotation, but I can't do it the other way around. So basically, for clockwise rotation, you need to multiply the transpose to a rotation matrix, but how do you do the same thing the other way around?
Here's my code:
public class rotation2 {
public static int [][] multiplyMatrix(int [][] m1) {
int [][] m2 = {{0,0,0,1},
{0,0,1,0},
{0,1,0,0},
{1,0,0,0}};
int[][] result = new int[4][4];
// multiply
for (int i=0; i<4; i++)
for (int j=0; j<4; j++)
for (int k=0; k<4; k++)
result[i][j] += m1[i][k] * m2[k][j];
return result;
}
public static int [][] multiplyMatrix2(int [][] m2) {
int [][] m1 = {{0,0,0,1},
{0,0,1,0},
{0,-1,0,0},
{-1,0,0,0}};
int[][] result = new int[4][4];
// multiply
for (int i=0; i<4; i++)
for (int j=0; j<4; j++)
for (int k=0; k<4; k++)
result[i][j] += m1[i][k] * m2[k][j];
return result;
}
public static void printArray(int [][] array) {
for(int row = 0; row < array.length; row++) {
for(int col = 0; col < array[row].length; col++) {
if (array[row][col] > 0) {
System.out.printf("1");
} else {
System.out.printf("0");
}
}
System.out.printf("\n");
}
}
public static int [][] transpose(int [][] m1) {
int m = 4;
int n = 4;
int c = 0;
int d = 0;
int[][] transpose = new int [n][m];
for ( c = 0 ; c < m ; c++ ) {
for ( d = 0 ; d < n ; d++ ) {
transpose[d][c] = m1[c][d];
}
}
return transpose;
}
public static void main(String[] args) {
int [][] m1 = {{1,0,0,0},
{1,0,0,0},
{1,1,0,0},
{0,0,0,0}};
int [][] transpose = transpose(m1);
printArray(transpose);
transpose = multiplyMatrix(transpose);
printArray(transpose);
int [][] transpose2 = transpose(m1);
printArray(transpose2);
transpose2 = multiplyMatrix(transpose2);
printArray(transpose2);
}
}
You don't transpose for counter clock rotation, right?

What you have to do is to (1) transpose the matrix, and (2) inverse the rows (clockwise) or columns (counter-clockwise), respectively.
You can just use a double-for-loop to set the new values for the individual cells, doing both steps at the same time. In code, this might look like this:
public static int[][] rotate(int[][] m, boolean left) {
int rows = m.length, cols = m[0].length;
int[][] m2 = new int[cols][rows]; // swap rows and cols
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols; c++)
if (left) // rotate left
m2[c][r] = m[r][cols - c - 1];
else // rotate right
m2[c][r] = m[rows - r - 1][c];
return m2;
}
For more information and alternative approaches, take a look at the answers to this related question.

Related

is there any way to simplify my code for matrix multiplication?

public class J1_LAB08_1 {
public static void main(String[] args) {
int r1 = 5, c1 = 3;//rows and column for matrix a
int r2 = 3, c2 = 4;//rows and column for matrix b
int matrixA[][] = new int[5][3];//initialize matrix a
System.out.println("Matrix A");
for (int i = 0; i < matrixA.length; i++) {
for (int j = 0; j < matrixA[i].length; j++) {//create random single integer matrix
matrixA[i][j] = ((int) (Math.random() * 10));
System.out.print(matrixA[i][j]);//print matrix a
}
System.out.println();
}
System.out.println();
System.out.println("Matrix B");
int matrixB[][] = new int[3][4];
for (int i = 0; i < matrixB.length; i++) {
for (int j = 0; j < matrixB[i].length; j++) {//create random single integer matrix
matrixB[i][j] = ((int) (Math.random() * 10));
System.out.print(matrixB[i][j]);//print matrix b
}
System.out.println();
}
System.out.println();
int[][] matrixC = multiplyMatrices(matrixA, matrixB, r1, c1, c2);//pass variables to multiply matrices function
printC(matrixC);//print matrix c
}
public static int[][] multiplyMatrices(int[][] matrixA, int[][] matrixB, int r1, int c1, int c2){//multiply the 2 given matrices and return the product
int[][] matrixC = new int[r1][c2];//initialize the product matrix using row a and column 2 as its parameters
for(int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
for (int k = 0; k < c1; k++) {
matrixC[i][j] += matrixA[i][k] * matrixB[k][j];//multiply using textbook formula
}
}
}
return matrixC;
}
public static void printC(int[][] matrixC) {//print the matrix
System.out.println("A x B is: ");
for(int[] row : matrixC) {
for (int column : row) {
System.out.print(column + " ");
}
System.out.println();
}
}
}
is there any way to simplify my code for matrix multiplication?
the resulting matrix should be 3 x 5 after multiplication
any help would be greatly appreciated, thank you for your time and consideration.

How can I print out the result matrix in my java code?

Create a basics.Matrix class (using a two-dimensional array of real numbers as a matrix) that has the following operations: construct an M × N zero matrix, construct an M × N matrix using an M × N array, create an N × N dimensional unit matrix ( the result matrix should be a return value), the matrix transposed resp. calculating the sum and difference of two matrices, representing the matrix as a string (use java.lang.StringBuilder to generate the text).
Also create a main program (Main.java) that tests these operations!
My problem is in my basicsMatrixMain.java code, that I do not know how can I print out thre results I get from difference or transpone. Can anybody help me to solve it ?
public class basicsMatrix {
private final int N;
private final int M;
private final double[][] matrix;
public basicsMatrix(int M, int N) {
this.N = N;
this.M = M;
matrix = new double[M][N];
}
public basicsMatrix(double[][] matrix) {
M = matrix.length;
N = matrix[0].length;
this.matrix = new double[N][M];
for (int i = 0; i < M; i++)
for (int j = 0; j < N; j++)
this.matrix[i][j] = matrix[i][j];
}
public void transzponalas(double[][] matrix1){
double[][] transpose = new double[M][N];
for(int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
transpose[j][i] = matrix1[i][j];
}
}
}
public void add(double[][] matrix1,double[][] matrix2){
double[][] osszeadas = new double[N][M];
for(int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
osszeadas[i][j] = (matrix1[i][j] + matrix2[i][j]);
}
}
}
public void difference(int matrix1[][], int matrix2[][]){
double[][] kivonas = new double[N][M];
for(int i = 0; i <= N; i++){
for(int j = 0; j <= M; j++){
kivonas[i][j] = matrix1[i][j] - matrix2[i][j];
}
}
}
public String matrixtostring(double[][] matrix1){
StringBuilder sb = new StringBuilder();
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
sb.append(matrix1);
}
}
return sb.toString();
}
}
public class basicsMatrixMain {
public static void main(String[] args) {
int N = 2;
int M = 3;
double[][] matrix1 = { {2, 3, 4}, {5, 2, 3} };
double[][] matrix2 = { {-4, 5, 3}, {5, 6, 3} };
System.out.println("\n");
System.out.print("Difference:");
for(int i = 0; i <= N; i++){
for(int j = 0; j <= M; j++){
System.out.println();
}
}
}
}
You have defined a lot of functions in basicsMatrix that you can use here.
However there are some changes that you need to make. In your add, difference and transpose methods, you define something but you never save the result. I would recommend something like this:
public double[][] transzponalas(double[][] matrix1){
double[][] transpose = new double[M][N];
for(int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
transpose[j][i] = matrix1[i][j];
}
}
return transpose;
}
public double[][] add(double[][] matrix1,double[][] matrix2){
double[][] osszeadas = new double[N][M];
for(int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
osszeadas[i][j] = (matrix1[i][j] + matrix2[i][j]);
}
}
return osszeadas;
}
public double[][] difference(int matrix1[][], int matrix2[][]){
double[][] kivonas = new double[N][M];
for(int i = 0; i <= N; i++){
for(int j = 0; j <= M; j++){
kivonas[i][j] = matrix1[i][j] - matrix2[i][j];
}
}
return kivonas;
}
All these functions now return a matrix that you can print out.
Now you just print you matrices. Something like this should work.
System.out.println(matrixtostring(transzponalas(matrix1)));
System.out.println(matrixtostring(add(matrix1,matrix2)));
System.out.println(matrixtostring(difference(matrix1,matrix2)));
Looking at the question description.
"Create a basics.Matrix class (using a two-dimensional array of real numbers as a matrix) that has the following operations: construct an M × N zero matrix, construct an M × N matrix using an M × N array, create an N × N dimensional unit matrix ( the result matrix should be a return value), the matrix transposed resp. calculating the sum and difference of two matrices, representing the matrix as a string (use java.lang.StringBuilder to generate the text).
Also create a main program (Main.java) that tests these operations!"
I suspect that you are supposed to create a class that calls functions on itself. In other words the basicsMatrix will become your matrix.
For example, the transzponalas method would become
public void transzponalas(){
double[][] transpose = new double[M][N];
for(int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
transpose[j][i] = this.matrix[i][j];
}
}
int tmp = this.M
this.M = this.N
this.N = tmp
this.matrix = transpose;
}
This way, you change the matrix that is inside your basicsMatrix. You should make sure that you understand the assignment correctly.

How to display the sum of two matrices from a method to main method in java?

How to display the sum of two matrices from a method to main method in java?
public static void main(String [] args) {
int ir1 = 5, ic1 = 3, ir2 = 5, ic2 = 3;
int [][] matrix1 = new int[ir1][ic1];
int [][] matrix2 = new int[ir2][ic2];
int[][] total = add (matrix1, matrix2);
System.out.println("\nThe addition of two Matrices: ");
for (int r = 0; r < total.length; r++) {
for (int c = 0; c < total[r].length; c++)
System.out.printf("%7d", total[r][c]);
System.out.println();
}
}
public static int [][] add (int[][] m1, int[][] m2) {
int ir1 = 0, ic1 = 0;
int total[][] = new int [ir1][ic1];
for (int r = 0; r < m1.length; r++) {
for (int c = 0; c < m2[r].length; c++) {
total [r][c] = m1[r][c] + m2[r][c];
}
}
return total;
}
//Assuming both array will have same dimensions.
public static int [][] add (int[][] m1, int[][] m2) {
int ir1 = m1.length, ic1 = m1[0].length;
int total[][] = new int [ir1][ic1];
for (int r = 0; r < ir1; r++) {
for (int c = 0; c < ic1; c++) {
total [r][c] = m1[r][c] + m2[r][c];
}
}
return total;
}

Chain Matrix Multiplication : Multiply Algorithm not working

I have implemented a chain matrix multiplication. Although I get correct chain order, but while doing actual multiplication, the given multiply algorithm is not working properly. My Java Code:-
package algopackage;
import java.util.ArrayList;
import java.util.List;
public class ChainMatrixMultiplication {
static int s[][];
static int x[][];
static int y[][];
public ChainMatrixMultiplication() {
}
static void chainMatrixMultiplication(int[] p) {
boolean isFirst = false;
int n = p.length-1;
int m[][] = new int[n][n];
s = new int[n][n];
for (int c = 0; c < n; c++)
m[c][c] = 0;
for (int counter = 1; counter < n; counter++) {
for (int i = 0;i < n; i++) {
isFirst = false;
int j = i + counter;
for (int k = i; k < j && j < n; k++) {
int result = m[i][k] + m[k+1][j] + p[i] * p[k+1] * p[j+1];
if (!isFirst) {
m[i][j] = result;
s[i][j] = k;
isFirst = true;
} else if (m[i][j] > result) {
m[i][j] = result;
s[i][j] = k;
}
}
}
}
}
static int[][] matrixMultiply(List<Matrix> matrices, int s[][], int i ,int j) {
if (i ==j) return matrices.get(i).getMatrix();
else {
int k = s[i][j];
x = matrixMultiply(matrices, s, i, k);
y = matrixMultiply(matrices, s, k+1, j);
return mult(x,y);
}
}
static int[][] mult(int[][] x, int[][] y) {
int [][] result = new int[x.length][y[0].length];
/* Loop through each and get product, then sum up and store the value */
for (int i = 0; i < x.length; i++) {
for (int j = 0; j < y[0].length; j++) {
for (int k = 0; k < x[0].length; k++) {
result[i][j] += x[i][k] * y[k][j];
}
}
}
return result;
}
public static void main(String[] args) {
int p[] = {5,4,6,2};
List<Matrix> matrices = new ArrayList<Matrix>();
Matrix m1 = new Matrix(5,4);
int arr[] = {1,2,40,2,3,29,10,21,11,120,23,90,24,12,11,1,11,45,23,21};
m1.addElementsToMatrix(5, 4, arr);
Matrix m2 = new Matrix(4,6);
int arr1[] = {1,1,1,2,3,12,12,3,10,12,12,29,22,11,22,11,11,11,13,1,2,12,4,2};
m2.addElementsToMatrix(4, 6, arr1);
Matrix m3 = new Matrix(6,2);
int arr2[] = {1,1,12,3,22,11,13,1,2,12,12,12};
m3.addElementsToMatrix(6, 2, arr2);
matrices.add(m1);
matrices.add(m2);
matrices.add(m3);
chainMatrixMultiplication(p);
matrixMultiply(matrices,s,0,2);
}
}
class Matrix {
private final int[][] matrix;
public Matrix(int rows, int cols) {
this.matrix = new int[rows][cols];
}
public void addElementsToMatrix(int rows, int cols, int[] arr) {
int counter = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = arr[counter++];
}
}
}
public int[][] getMatrix() {
return matrix;
}
}
In the above code matrixMultiply() function is throwing exception. Exception is caused as matrices are not being multiplied as expected. As recursion is not behaving as expected. I am missing something in this code. Any help will be appreciated.Thanks!
I'm not sure of the correctness of your code, but looking at the matrix multiplication output when you multiply matrix of dimension a*b and c*d after you multiply, you get a matrix of dimension a*d there by changing
for (int k = 0; k < x[0].length; k++) {
to
for (int k = 0; k < y[0].length; k++) {
should resolve the problem.
This:
x = matrixMultiply(matrices, s, i, k); // call A
y = matrixMultiply(matrices, s, k+1, j); // call B
return mult(x,y);
looks like it should multiply the result of call A by the result of call B. But in general, it doesn't.
x is not local, call B will usually overwrite it, except when call B immediately hits the base case.
This sort of thing tends to happen when you pass data around "to the side", not as function parameter or function return value. It is not reasonable to avoid that kind of data flow all the time, but you should avoid it here, especially since it's not even what you wanted.

Java deepToString to array - matrix multiplication

Can someone help me with something?
I'm trying to convert a string which was initially created using the deepToString() method, back to an array. I've tried pretty much anything I could find on Stack Overflow… but no luck.
This is what I have right now:
import java.util.*;
public class Test3 {
static int matrix [][] = new int[2][2];
public static int[][] matrixGenerator() {
Random r = new Random( );
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = r.nextInt( 10000 );
}
}
return matrix;
}
public static void main(String args[]){
String matrix1 = Arrays.deepToString(matrixGenerator());
String matrix2 = Arrays.deepToString(matrixGenerator());
System.out.println(matrix1 + '\n' + matrix2);
}
}
This outputs
[[6030, 3761], [6605, 5582]]
and
[[1799, 461], [1197, 1012]]
Which is exactly what I need. Now I'm trying to do a matrix multiplication using this piece of code.
int m1rows = matrix1.length;
int m1cols = matrix1[0].length;
int m2cols = matrix2[0].length;
int[][] result = new int[m1rows][m2cols];
for (int i = 0; i < m1rows; i++) {
for (int j = 0; j < m2cols; j++) {
for (int k = 0; k < m1cols; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
The problem is that I cannot loop through the array because it's not actually an array, it's a string. Which makes sense. Can someone tell me how can I loop, though? I've tried to convert the string back to array - but no luck
Why do you need convertion of matrix to String and then back to matrix?
Can you simply use
public static void main(String[] args) {
int matrix1 [][] = matrixGenerator();
int matrix2 [][] = matrixGenerator();
int matrix3 [][] = matrixMultiplication(matrix1, matrix2);
String matrix1Str = Arrays.deepToString(matrix1);
String matrix2Str = Arrays.deepToString(matrix2);
String matrix3Str = Arrays.deepToString(matrix3);
System.out.println(matrix1Str+'\n'+matrix2Str+'\n'+matrix3Str);
}
public static int[][] matrixGenerator(){
int matrix [][] = new int[2][2];
Random r = new Random( );
for(int i=0; i < matrix.length; i++){
for(int j=0; j < matrix[i].length; j++){
matrix[i][j] = r.nextInt( 10000 );
}
}
return matrix;
}
public static int[][] matrixMultiplication(int[][] matrix1, int[][] matrix2) {
int m1rows = matrix1.length;
int m1cols = matrix1[0].length;
int m2cols = matrix2[0].length;
int[][] result = new int[m1rows][m2cols];
for (int i=0; i< m1rows; i++){
for (int j=0; j< m2cols; j++){
for (int k=0; k< m1cols; k++){
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
return result;
}

Categories