medon3

Compare 2D Matrices

Apr 12th, 2022
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class Compare2DMatrices {
  4.  
  5. public static void main(String[] args) {
  6.  
  7. Scanner sc = new Scanner(System.in);
  8.  
  9. String[] values1 = sc.nextLine().split(" ");
  10. int rows1 = Integer.parseInt(values1[0]);
  11. int columns1 = Integer.parseInt(values1[1]);
  12. String elements1 = "";
  13.  
  14. for (int i = 0; i < rows1; i++) {
  15. elements1 = sc.nextLine();
  16. }
  17.  
  18. int[][] matrix1 = readMatrix(rows1, columns1, elements1);
  19.  
  20. String[] values2 = sc.nextLine().split(" ");
  21. int rows2 = Integer.parseInt(values2[0]);
  22. int columns2 = Integer.parseInt(values2[1]);
  23. String elements2 = "";
  24.  
  25. for (int i = 0; i < rows1; i++) {
  26. elements2 = sc.nextLine();
  27. }
  28.  
  29. int[][] matrix2 = readMatrix(rows2, columns2,elements2);
  30.  
  31. if (matrix1.length != matrix2.length ||
  32. matrix1[0].length != matrix2[0].length) {
  33. System.out.println("not equal");
  34. return;
  35. }
  36.  
  37. for (int row = 0; row < matrix1.length; row++) {
  38. for (int col = 0; col < matrix1[row].length; col++) {
  39. if (matrix1[row][col] != matrix2[row][col]) {
  40. System.out.println("not equal");
  41. return;
  42. }
  43. }
  44. }
  45. System.out.println("equal");
  46.  
  47. }
  48.  
  49. private static int[][] readMatrix(int rows, int columns, String input) {
  50.  
  51. Scanner sc = new Scanner(System.in);
  52.  
  53. int[][] matrix = new int[rows][columns];
  54. for (int row = 0; row < rows; row++) {
  55. String[] inputElements = input.split(" ");
  56. for (int col = 0; col < columns; col++) {
  57. matrix[row][col] = Integer.parseInt(inputElements[col]);
  58.  
  59. }
  60. }
  61. return matrix;
  62. }
  63.  
  64. }
  65.  
  66.  
  67.  
Advertisement
Add Comment
Please, Sign In to add comment