Guest User

Untitled

a guest
Nov 23rd, 2017
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. public class MatrixTransposer {
  2.  
  3. public static int[][] transpose(int[][] matrix) throws IllegalArgumentException {
  4. if(matrix.length == 0) {
  5. throw new IllegalArgumentException("Empty array");
  6. }
  7. int rowLength = matrix[0].length;
  8. for (int[] ai:matrix) {
  9. if (rowLength != ai.length) {
  10. throw new IllegalArgumentException("Non-equal rows");
  11. }
  12. }
  13.  
  14. int [][] tMatrix = new int[rowLength][];
  15. for (int i = 0; i < rowLength; i++) {
  16. tMatrix[i] = new int[matrix.length];
  17. }
  18. for (int i = 0; i < matrix.length; i++) {
  19. int[] tArr = matrix[i];
  20. for (int j = 0; j < rowLength; j++) {
  21. tMatrix[j][i] = tArr[j];
  22. }
  23. }
  24. return tMatrix;
  25. }
  26.  
  27. public static void main(String[] args) {
  28. int[][] a = new int[2][4];
  29. int counter = 0;
  30. for (int[] ai:a) {
  31. for (int i = 0; i < ai.length; i++) {
  32. ai[i] = counter++;
  33. }
  34. }
  35. try {
  36. a = transpose(a);
  37. } catch (IllegalArgumentException e) {
  38. e.printStackTrace();
  39. }
  40. for(int[] ai:a) {
  41. for (int aai:ai) {
  42. System.out.print(aai);
  43. System.out.print("; ");
  44. }
  45. System.out.println();
  46. }
  47. }
  48.  
  49. }
Add Comment
Please, Sign In to add comment