Advertisement
svetlyo0659

Untitled

Feb 26th, 2020
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.27 KB | None | 0 0
  1. import java.util.Arrays;
  2. import java.util.Random;
  3.  
  4. public class Matrices
  5. {
  6.  
  7.   public static int[][] createMatrix(int row, int col)
  8.   {
  9.     Random random = new Random();
  10.     int[][] matrix = new int[row][col];
  11.     for (int i = 0; i < row; i++) {
  12.       for (int j = 0; j < col; j++) {
  13.         matrix[i][j] = random.nextInt(10);
  14.       }
  15.     }
  16.     return matrix;
  17.   }
  18.  
  19.  
  20.   public static void main(String[] args)
  21.   {
  22.  
  23.     int[][] firstMatrix = createMatrix(2, 2); //
  24.     int[][] secondMatrix = createMatrix(2, 2);
  25.     int[][] resultSumOfMatrices = new int[firstMatrix.length][firstMatrix.length];
  26.     int[][] resultDirectSumOfMatrices = new int[firstMatrix.length][firstMatrix.length];
  27.  
  28.     for (int i = 0; i < firstMatrix.length; i++) {   /// prints the two Matrices side by side
  29.       for (int j = 0; j < firstMatrix[i].length; ++j) {
  30.         System.out.print("  " + firstMatrix[i][j]);
  31.       }
  32.       System.out.print("  |");
  33.       for (int k = 0; k < secondMatrix[i].length; ++k) {
  34.         System.out.print("  " + secondMatrix[i][k]);
  35.       }
  36.       System.out.println();
  37.     }
  38.  
  39.     System.out.println();
  40.  
  41.     for (int i = 0; i < firstMatrix.length; i++) {   /// adds and prints the value of the first and second matrices
  42.       for (int j = 0; j < firstMatrix[i].length; ++j) {
  43.         resultSumOfMatrices[i][j] = firstMatrix[i][j] + secondMatrix[i][j];
  44.         System.out.print("  " + resultSumOfMatrices[i][j] );
  45.       }
  46.       System.out.println();
  47.     }
  48.  
  49.     System.out.println(); // empty line
  50.  
  51.     for (int i = 0; i < resultDirectSumOfMatrices.length; i++) { /// prints the first half of the direct sum
  52.       for (int j = 0; j < firstMatrix[i].length; ++j) {
  53.         System.out.print("  " + firstMatrix[i][j]);
  54.       }
  55.       for (int j = 0; j < resultDirectSumOfMatrices.length; j++) {
  56.         System.out.print("  " + 0);
  57.       }
  58.  
  59.       System.out.println();
  60.  
  61.     }
  62.  
  63.     for (int i = 0; i < resultDirectSumOfMatrices.length; i++) { /// prints the second half of the direct sum
  64.       for (int j = 0; j < resultDirectSumOfMatrices.length; j++) {
  65.         System.out.print("  " + 0);
  66.       }
  67.       for (int k = 0; k < secondMatrix[i].length; ++k) {
  68.         System.out.print("  " + secondMatrix[i][k]);
  69.       }
  70.  
  71.       System.out.println();
  72.     }
  73.  
  74.   }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement