Created
September 25, 2012 04:32
-
-
Save jmdeldin/3780000 to your computer and use it in GitHub Desktop.
Matrix rotation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// -*- compile-command: "javac -Xlint Matrix.java && java Matrix" -*- | |
import java.lang.Math; | |
/** | |
* Square matrix class. | |
* | |
* @author Jon-Michael Deldin <[email protected]> | |
*/ | |
public class Matrix { | |
private int N; | |
private char[][] mat; | |
public Matrix(char[][] mat) { | |
this.mat = mat; | |
this.N = mat.length; | |
} | |
/** | |
* Rotate the matrix 90º clockwise. | |
* | |
*/ | |
public void rotate90cw() { | |
char[][] ret = new char[N][N]; | |
int newX; | |
for (int i = 0; i < N; i++) { | |
for (int j = 0; j < N; j++) { | |
newX = N - 1 - i; | |
ret[j][newX] = mat[i][j]; | |
} | |
} | |
mat = ret; | |
} | |
public String toString() { | |
StringBuilder sb = new StringBuilder(); | |
for (int i = 0; i < N; i++) { | |
for (int j = 0; j< N; j++) { | |
sb.append(mat[i][j]); | |
sb.append(" "); | |
} | |
sb.append("\n"); | |
} | |
return sb.toString(); | |
} | |
public void print() { | |
System.out.print(this); | |
} | |
public static void main(String[] args) { | |
Matrix mat = new Matrix(new char[][] { | |
{'a', 'b', 'c'}, | |
{'d', 'e', 'f'}, | |
{'g', 'h', 'i'}, | |
}); | |
mat.print(); | |
System.out.println(); | |
mat.rotate90cw(); | |
mat.print(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment