DAS_2024_1/Matrix.cs

132 lines
3.6 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace rvip_6
{
public class Matrix
{
private readonly double[,] data;
public int Size { get; }
public Matrix(int size)
{
Size = size;
data = new double[size, size];
FillRandom();
}
public Matrix(double[,] data)
{
this.data = data;
Size = data.GetLength(0);
}
public double GetElement(int row, int col)
{
return data[row, col];
}
public void SetElement(int row, int col, double value)
{
data[row, col] = value;
}
private void FillRandom()
{
Random random = new Random();
for (int i = 0; i < Size; i++)
{
for (int j = 0; j < Size; j++)
{
data[i, j] = random.NextDouble() * 10; // Заполняем случайными числами (0 - 10)
}
}
}
public double DeterminantSequential()
{
if (Size == 1)
return data[0, 0];
if (Size == 2)
return data[0, 0] * data[1, 1] - data[0, 1] * data[1, 0];
double det = 0;
for (int j = 0; j < Size; j++)
{
det += (j % 2 == 0 ? 1 : -1) * data[0, j] * GetSubMatrix(0, j).DeterminantSequential();
}
return det;
}
private Matrix GetSubMatrix(int rowToRemove, int colToRemove)
{
double[,] subMatrix = new double[Size - 1, Size - 1];
int subRow = 0;
for (int row = 0; row < Size; row++)
{
if (row == rowToRemove)
continue;
int subCol = 0;
for (int col = 0; col < Size; col++)
{
if (col == colToRemove)
continue;
subMatrix[subRow, subCol] = data[row, col];
subCol++;
}
subRow++;
}
return new Matrix(subMatrix);
}
public double DeterminantParallel(int numThreads)
{
if (Size == 1)
return data[0, 0];
if (Size == 2)
return data[0, 0] * data[1, 1] - data[0, 1] * data[1, 0];
double det = 0;
var results = new double[Size];
var tasks = new Task[Size];
for (int j = 0; j < Size; j++)
{
int currentJ = j;
tasks[j] = Task.Run(() =>
{
results[currentJ] = (currentJ % 2 == 0 ? 1 : -1) * data[0, currentJ] * GetSubMatrix(0, currentJ).DeterminantParallel(numThreads);
});
}
Task.WaitAll(tasks);
for (int i = 0; i < results.Length; i++)
{
det += results[i];
}
return det;
}
public override string ToString()
{
string result = "";
for (int i = 0; i < Size; i++)
{
for (int j = 0; j < Size; j++)
{
result += data[i, j] + " ";
}
result += "\n";
}
return result;
}
}
}