Didart

Fill the Matrix

Jan 14th, 2023
492
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.71 KB | None | 0 0
  1. package MultidimensionalArrays2;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class FillTheMatrix {
  6.     public static void main(String[] args) {
  7.         Scanner scanner = new Scanner(System.in);
  8.  
  9.         String[] line = scanner.nextLine().split(", ");
  10.         int matSize = Integer.parseInt(line[0]);
  11.         char pattern = line[1].charAt(0);
  12.         int num = 1;
  13.         int row;
  14.         int col;
  15.  
  16.         int[][] matrix = new int[matSize][matSize];
  17.  
  18.         switch (pattern) {
  19.             case 'A':
  20.                 for (col = 0; col < matSize; col++) {
  21.                     for (row = 0; row < matSize; row++) {
  22.                         matrix[row][col] = num;
  23.                         num++;
  24.                     }
  25.                 }
  26.                 PrintMatrix(matrix);
  27.                 break;
  28.             case 'B':
  29.                 for (col = 0; col < matSize; col++) {
  30.                     if (col % 2 == 0) {
  31.                         for (row = 0; row < matSize; row++) {
  32.                             matrix[row][col] = num;
  33.                             num++;
  34.                         }
  35.                     } else {
  36.                         for (row = matSize - 1; row >= 0; row--) {
  37.                             matrix[row][col] = num;
  38.                             num++;
  39.                         }
  40.                     }
  41.                 }
  42.                 PrintMatrix(matrix);
  43.                 break;
  44.         }
  45.     }
  46.    
  47.     private static void PrintMatrix(int[][] matrix) {
  48.         for (int row = 0; row < matrix.length; row++) {
  49.             for (int col = 0; col < matrix[0].length; col++) {
  50.                 System.out.print(matrix[row][col] + " ");
  51.             }
  52.             System.out.println();
  53.         }
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment