-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMatrixMultiplier.cs
More file actions
63 lines (59 loc) · 2.19 KB
/
MatrixMultiplier.cs
File metadata and controls
63 lines (59 loc) · 2.19 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace Lab1.Wpf
{
public static class MatrixMultiplier
{
/// <summary>
/// Генерирует случайную целочисленную матрицу size×size,
/// где каждый элемент — в диапазоне [minValue, maxValue).
/// </summary>
public static int[,] RandomMatrix(int size, int minValue, int maxValue, Random rng)
{
var M = new int[size, size];
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
M[i, j] = rng.Next(minValue, maxValue);
return M;
}
/// <summary>
/// Генерирует целочисленную матрицу rows×cols.
/// </summary>
public static int[,] RandomMatrix(int rows, int cols, int minValue, int maxValue, Random rng)
{
var M = new int[rows, cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
M[i, j] = rng.Next(minValue, maxValue);
return M;
}
/// <summary>
/// Умножение прямоугольных матриц: A (rows × inner) * B (inner × cols) = C (rows × cols)
/// Ожидается, что A.GetLength(1) == B.GetLength(0)
/// </summary>
public static int[,] Multiply(int[,] A, int[,] B)
{
int rows = A.GetLength(0);
int inner = A.GetLength(1);
int cols = B.GetLength(1);
var C = new int[rows, cols];
for (int i = 0; i < rows; i++)
{
for (int k = 0; k < inner; k++)
{
int aik = A[i, k];
if (aik == 0) continue; // небольшая оптимизация для разрежённых матриц
for (int j = 0; j < cols; j++)
{
C[i, j] += aik * B[k, j];
}
}
}
return C;
}
}
}