Ligh7_of_H3av3n

03. Intersection of Two Matrices

May 16th, 2024
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.57 KB | None | 0 0
  1. package Lekciq;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class IntersectionOfTwoMatrices {
  6.     public static void main(String[] args) {
  7.         Scanner scanner = new Scanner(System.in);
  8.  
  9.  
  10.         // Read the dimensions of the matrices
  11.         int M = scanner.nextInt();
  12.         int N = scanner.nextInt();
  13.  
  14.         // Read the first matrix
  15.         char[][] A = readMatrix(scanner, M, N);
  16.  
  17.         // Read the second matrix
  18.         char[][] B = readMatrix(scanner, M, N);
  19.  
  20.         // Create and fill the third matrix C with intersecting elements
  21.         char[][] C = new char[M][N];
  22.         for (int i = 0; i < M; i++) {
  23.             for (int j = 0; j < N; j++) {
  24.                 if (A[i][j] == B[i][j]) {
  25.                     C[i][j] = A[i][j];
  26.                 } else {
  27.                     C[i][j] = '*';
  28.                 }
  29.             }
  30.         }
  31.  
  32.         // Print the third matrix C
  33.         printMatrix(C);
  34.     }
  35.  
  36.     // Method to read a matrix from the console
  37.     private static char[][] readMatrix(Scanner scanner, int rows, int cols) {
  38.         char[][] matrix = new char[rows][cols];
  39.         for (int i = 0; i < rows; i++) {
  40.             for (int j = 0; j < cols; j++) {
  41.                 matrix[i][j] = scanner.next().charAt(0);
  42.             }
  43.         }
  44.         return matrix;
  45.     }
  46.  
  47.     // Method to print a matrix
  48.     private static void printMatrix(char[][] matrix) {
  49.         for (char[] row : matrix) {
  50.             for (char element : row) {
  51.                 System.out.print(element + " ");
  52.             }
  53.             System.out.println();
  54.         }
  55.     }
  56. }
  57.  
Advertisement
Add Comment
Please, Sign In to add comment