Advertisement
Ligh7_of_H3av3n

01. Fill the Matrix

May 17th, 2024
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.84 KB | None | 0 0
  1. package Uprajnenie;
  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.  
  10.  
  11.         String input = scanner.nextLine();
  12.         String[] inputs = input.split(" ");
  13.         int N = Integer.parseInt(inputs[0].replace(",", ""));
  14.         char patternType = inputs[1].charAt(0);
  15.  
  16.         int[][] matrix = new int[N][N];
  17.  
  18.         if (patternType == 'A') {
  19.             fillPatternA(matrix, N);
  20.         } else if (patternType == 'B') {
  21.             fillPatternB(matrix, N);
  22.         } else {
  23.             System.out.println("Invalid pattern type. Please enter 'A' or 'B'.");
  24.             return;
  25.         }
  26.  
  27.         printMatrix(matrix, N);
  28.     }
  29.  
  30.     // Method to fill the matrix with Pattern A
  31.     public static void fillPatternA(int[][] matrix, int N) {
  32.         int num = 1;
  33.         for (int col = 0; col < N; col++) {
  34.             for (int row = 0; row < N; row++) {
  35.                 matrix[row][col] = num++;
  36.             }
  37.         }
  38.     }
  39.  
  40.     // Method to fill the matrix with Pattern B
  41.     public static void fillPatternB(int[][] matrix, int N) {
  42.         int num = 1;
  43.         for (int col = 0; col < N; col++) {
  44.             if (col % 2 == 0) {
  45.                 for (int row = 0; row < N; row++) {
  46.                     matrix[row][col] = num++;
  47.                 }
  48.             } else {
  49.                 for (int row = N - 1; row >= 0; row--) {
  50.                     matrix[row][col] = num++;
  51.                 }
  52.             }
  53.         }
  54.     }
  55.  
  56.     // Method to print the matrix
  57.     public static void printMatrix(int[][] matrix, int N) {
  58.         for (int i = 0; i < N; i++) {
  59.             for (int j = 0; j < N; j++) {
  60.                 System.out.print(matrix[i][j] + " ");
  61.             }
  62.             System.out.println();
  63.         }
  64.     }
  65. }
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement