-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlab1.java
More file actions
100 lines (86 loc) · 2.94 KB
/
lab1.java
File metadata and controls
100 lines (86 loc) · 2.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/*
Тітов С.О. ІО-35
Дія з матрицями - 4
Тип елементів - int
Дія з матрицею -2
*/
import java.util.Random;
public class lab1 {
public static void main(String[] args) {
try {
int ra = 3;
int ca = 4;
int rb = 4;
int cb = 3;
int[][] A = GenerateMatrix(ra, ca);
int[][] B = GenerateMatrix(rb, cb);
System.out.println("Матриця A:");
PrintMatrix(A);
System.out.println("\nМатриця B:");
PrintMatrix(B);
int[][] C = MultiplyMatrices(A, B);
System.out.println("\nРезультуюча матриця C = A * B:");
PrintMatrix(C);
int sumMax = ColumnSum(C);
System.out.println("\nСума найбiльших елементiв кожного стовпця матрицi C = " + sumMax);
} catch (Exception e) {
System.err.println("Помилка: " + e.getMessage());
}
}
// Генерація матриці з випадковими цілими числами
private static int[][] GenerateMatrix(int rows, int cols) {
Random random = new Random();
int[][] matrix = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = random.nextInt(10);
}
}
return matrix;
}
// Множення матриць
private static int[][] MultiplyMatrices(int[][] A, int[][] B) {
if (A[0].length != B.length) {
throw new IllegalArgumentException("Несумісні розміри матриць.");
}
int rows = A.length;
int cols = B[0].length;
int common = A[0].length;
int[][] result = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
int sum = 0;
for (int k = 0; k < common; k++) {
sum += A[i][k] * B[k][j];
}
result[i][j] = sum;
}
}
return result;
}
// Сума найбільших елементів кожного стовпця
private static int ColumnSum(int[][] matrix) {
int rows = matrix.length;
int cols = matrix[0].length;
int sum = 0;
for (int j = 0; j < cols; j++) {
int max = matrix[0][j];
for (int i = 1; i < rows; i++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
}
}
sum += max;
}
return sum;
}
// Вивід матриці
private static void PrintMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int elem : row) {
System.out.printf("%4d", elem);
}
System.out.println();
}
}
}