Advertisement
Ligh7_of_H3av3n

01. Compare Matrices

May 16th, 2024
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.56 KB | None | 0 0
  1. package Lekciq;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class CompareMatrices {
  6.     public static void main(String[] args) {
  7.         Scanner scanner = new Scanner(System.in);
  8.  
  9.  
  10.         // Read the first matrix
  11.         int[][] matrix1 = readMatrix(scanner);
  12.  
  13.         // Read the second matrix
  14.         int[][] matrix2 = readMatrix(scanner);
  15.  
  16.         // Compare the matrices and print the result
  17.         if (areMatricesEqual(matrix1, matrix2)) {
  18.             System.out.println("equal");
  19.         } else {
  20.             System.out.println("not equal");
  21.         }
  22.     }
  23.  
  24.     // Method to read a matrix from the console
  25.     private static int[][] readMatrix(Scanner scanner) {
  26.         int rows = scanner.nextInt();
  27.         int cols = scanner.nextInt();
  28.         int[][] matrix = new int[rows][cols];
  29.  
  30.         // Read matrix elements
  31.         for (int i = 0; i < rows; i++) {
  32.             for (int j = 0; j < cols; j++) {
  33.                 matrix[i][j] = scanner.nextInt();
  34.             }
  35.         }
  36.         return matrix;
  37.     }
  38.  
  39.     // Method to compare two matrices element by element
  40.     private static boolean areMatricesEqual(int[][] matrix1, int[][] matrix2) {
  41.         if (matrix1.length != matrix2.length || matrix1[0].length != matrix2[0].length) {
  42.             return false;
  43.         }
  44.  
  45.         for (int i = 0; i < matrix1.length; i++) {
  46.             for (int j = 0; j < matrix1[0].length; j++) {
  47.                 if (matrix1[i][j] != matrix2[i][j]) {
  48.                     return false;
  49.                 }
  50.             }
  51.         }
  52.         return true;
  53.     }
  54. }
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement