Advertisement
Guest User

Untitled

a guest
Jan 20th, 2019
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. package excersies.ex1_fill_the_matrix;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class FillTheMatrix {
  6. public static void main(String[] args) {
  7.  
  8. Scanner scanner = new Scanner(System.in);
  9.  
  10. String[] input = scanner.nextLine().split(", ");
  11. int dimensions = Integer.parseInt(input[0]);
  12. String type = input[1].toLowerCase();
  13.  
  14. int[][] matrix = createMatrix(dimensions);
  15.  
  16. if (type.equals("a")) {
  17. fillTypeA(matrix);
  18. } else if (type.equals("b")) {
  19. fillTypeB(matrix);
  20. }
  21.  
  22. System.out.println(showMatrix(matrix).toString());
  23. }
  24.  
  25. private static int[][] createMatrix(int dimensions) {
  26. return new int[dimensions][dimensions];
  27. }
  28.  
  29. private static void fillTypeA(int[][] matrix) {
  30.  
  31. int rows = matrix.length;
  32. int cols = matrix[0].length;
  33.  
  34. int rowEntity = 1;
  35. for (int col = 0; col < cols; col++) {
  36. for (int row = 0; row < rows; row++) {
  37.  
  38. matrix[row][col] = rowEntity;
  39. rowEntity++;
  40. }
  41. }
  42. }
  43.  
  44. private static void fillTypeB(int[][] matrix) {
  45.  
  46. int rows = matrix.length;
  47. int cols = matrix[0].length;
  48.  
  49. int col = 0;
  50. int rowEntity = 1;
  51.  
  52. for (col = 0; col < cols; col++) {
  53. if (col % 2 == 0) {
  54. for (int row = 0; row < rows; row++) {
  55.  
  56. matrix[row][col] = rowEntity;
  57. rowEntity++;
  58. }
  59. } else {
  60. for (int row = rows - 1; row >= 0; row--) {
  61.  
  62. matrix[row][col] = rowEntity;
  63. rowEntity++;
  64. }
  65. }
  66. }
  67. }
  68.  
  69. private static StringBuilder showMatrix(int[][] matrix) {
  70.  
  71. int rows = matrix.length;
  72. int cols = matrix[0].length;
  73.  
  74. StringBuilder output = new StringBuilder();
  75. for (int row = 0; row < rows; row++) {
  76. for (int col = 0; col < cols; col++) {
  77.  
  78. output.append(matrix[row][col])
  79. .append(" ");
  80. }
  81. output.append(System.lineSeparator());
  82. }
  83. return output;
  84. }
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement