distributed-computing/tasks/savitskiy-al/lab_5/ConsoleApp1/ConsoleApp1/MatrixHelper.cs
2023-12-15 21:02:23 +04:00

57 lines
1.6 KiB
C#

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
public class MatrixService
{
static readonly Random rand = new Random();
public int[,] RandomGenerateMatrix(int dimensionsCount)
{
int[,] result = new int[dimensionsCount, dimensionsCount];
for (int i = 0; i < dimensionsCount; i++)
{
for (int j = 0; j < dimensionsCount; j++)
{
result[i, j] = rand.Next(1000);
}
}
return result;
}
public int[,] MultiplicationMatrix(int[,] matrix1, int[,] matrix2, int threadCount)
{
var result = new int[matrix1.GetLength(0), matrix1.GetLength(1)];
for(int i = 0; i < result.GetLength(0); i++)
{
for (int j = 0; j < result.GetLength(1); j++)
{
result[i, j] = 0;
}
}
for (int i = 0; i < matrix1.GetLength(0); i++)
{
Parallel.For(0, matrix2.GetLength(1), new ParallelOptions() { MaxDegreeOfParallelism = threadCount },
(j) =>
{
for (int k = 0; k < matrix2.GetLength(0); k++)
{
var value = matrix1[i, k] * matrix2[k, j];
Interlocked.Add(ref result[i, j], value);
}
});
}
return result;
}
}
}