Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class MatrixTransposer {
- public static int[][] transpose(int[][] matrix) throws IllegalArgumentException {
- if(matrix.length == 0) {
- throw new IllegalArgumentException("Empty array");
- }
- int rowLength = matrix[0].length;
- for (int[] ai:matrix) {
- if (rowLength != ai.length) {
- throw new IllegalArgumentException("Non-equal rows");
- }
- }
- int [][] tMatrix = new int[rowLength][];
- for (int i = 0; i < rowLength; i++) {
- tMatrix[i] = new int[matrix.length];
- }
- for (int i = 0; i < matrix.length; i++) {
- int[] tArr = matrix[i];
- for (int j = 0; j < rowLength; j++) {
- tMatrix[j][i] = tArr[j];
- }
- }
- return tMatrix;
- }
- public static void main(String[] args) {
- int[][] a = new int[2][4];
- int counter = 0;
- for (int[] ai:a) {
- for (int i = 0; i < ai.length; i++) {
- ai[i] = counter++;
- }
- }
- try {
- a = transpose(a);
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- }
- for(int[] ai:a) {
- for (int aai:ai) {
- System.out.print(aai);
- System.out.print("; ");
- }
- System.out.println();
- }
- }
- }
Add Comment
Please, Sign In to add comment