distributed-computing/tasks/mironov-eo/lab_5/ConsoleApp1/ConsoleApp1/MatrixHelper.cs
2023-12-06 13:58:56 +03:00

58 lines
1.8 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 MatrixHelper
{
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(10000);
}
}
return result;
}
public int[][] MultiplicationMatrix(int[,] firstMatrix, int[,] secondMatrix, int threadCount = 1)
{
var resultMatrix = new ConcurrentDictionary<int, int>[firstMatrix.GetLength(0)]
.Select(x => new ConcurrentDictionary<int, int>())
.ToArray();
for (int i = 0; i < firstMatrix.GetLength(0); i++)
{
Parallel.For(0, secondMatrix.GetLength(1), new ParallelOptions()
{
MaxDegreeOfParallelism = threadCount
},
(j) =>
{
for (int k = 0; k < secondMatrix.GetLength(0); k++)
{
resultMatrix[i].AddOrUpdate(
j,
firstMatrix[i, k] * secondMatrix[k, j],
(key, value) => value + firstMatrix[i, k] * secondMatrix[k, j]);
}
});
}
return resultMatrix
.Select(x => x.Values.ToArray())
.ToArray();
}
}
}