java - How do we rotate a tetris piece counter clockwise? -
i looked @ algorithm here clockwise rotation, can't other way around. basically, clockwise rotation, need multiply transpose rotation matrix, how do same thing other way around?
here's 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 (int i=0; i<4; i++) (int j=0; j<4; j++) (int k=0; k<4; k++) result[i][j] += m1[i][k] * m2[k][j]; homecoming 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 (int i=0; i<4; i++) (int j=0; j<4; j++) (int k=0; k<4; k++) result[i][j] += m1[i][k] * m2[k][j]; homecoming 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]; ( c = 0 ; c < m ; c++ ) { ( d = 0 ; d < n ; d++ ) { transpose[d][c] = m1[c][d]; } } homecoming 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 counter clock rotation, right?
what have (1) transpose matrix, , (2) inverse rows (clockwise) or columns (counter-clockwise), respectively.
you can utilize double-for-loop set new values individual cells, doing both steps @ same time. in code, might 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 , cols (int r = 0; r < rows; r++) (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]; homecoming m2; } for more info , alternative approaches, take @ answers this related question.
java matrix rotation
No comments:
Post a Comment