111 lines
3.0 KiB
C#
111 lines
3.0 KiB
C#
namespace ConsoleApp1
|
|
{
|
|
|
|
public class MatrixService
|
|
{
|
|
|
|
static readonly Random rand = new Random();
|
|
|
|
object lockObject = new object();
|
|
|
|
|
|
public double[,] RandomGenerateMatrix(int dimensionsCount)
|
|
{
|
|
double[,] result = new double[dimensionsCount, dimensionsCount];
|
|
for (int i = 0; i < dimensionsCount; i++)
|
|
{
|
|
for (int j = 0; j < dimensionsCount; j++)
|
|
{
|
|
result[i, j] = rand.NextDouble() * 10;
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
|
|
public double DeterminantOfMatrix(double[,] matrix, int threadCount)
|
|
{
|
|
int size = matrix.GetLength(0);
|
|
|
|
if (size == 1)
|
|
{
|
|
return matrix[0, 0];
|
|
}
|
|
else if (size == 2)
|
|
{
|
|
return matrix[0, 0] * matrix[1, 1] - matrix[0, 1] * matrix[1, 0];
|
|
}
|
|
else
|
|
{
|
|
double determinant = 0;
|
|
|
|
Parallel.For(0, size, new ParallelOptions { MaxDegreeOfParallelism = threadCount },
|
|
(i) =>
|
|
{
|
|
double[,] subMatrix = GetSubMatrix(matrix, i);
|
|
double subDeterminant = matrix[0, i] * Determinant(subMatrix);
|
|
double value = Math.Pow(-1, i) * subDeterminant;
|
|
lock (lockObject)
|
|
{
|
|
determinant += value;
|
|
}
|
|
});
|
|
|
|
return determinant;
|
|
}
|
|
}
|
|
|
|
static double[,] GetSubMatrix(double[,] matrix, int columnIndex)
|
|
{
|
|
int size = matrix.GetLength(0);
|
|
double[,] subMatrix = new double[size - 1, size - 1];
|
|
|
|
for (int i = 1; i < size; i++)
|
|
{
|
|
for (int j = 0; j < size; j++)
|
|
{
|
|
if (j < columnIndex)
|
|
{
|
|
subMatrix[i - 1, j] = matrix[i, j];
|
|
}
|
|
else if (j > columnIndex)
|
|
{
|
|
subMatrix[i - 1, j - 1] = matrix[i, j];
|
|
}
|
|
}
|
|
}
|
|
|
|
return subMatrix;
|
|
}
|
|
|
|
static double Determinant(double[,] matrix)
|
|
{
|
|
int size = matrix.GetLength(0);
|
|
|
|
if (size == 1)
|
|
{
|
|
return matrix[0, 0];
|
|
}
|
|
else if (size == 2)
|
|
{
|
|
return matrix[0, 0] * matrix[1, 1] - matrix[0, 1] * matrix[1, 0];
|
|
}
|
|
else
|
|
{
|
|
double determinant = 0;
|
|
|
|
for (int i = 0; i < size; i++)
|
|
{
|
|
double[,] subMatrix = GetSubMatrix(matrix, i);
|
|
|
|
determinant += (int)Math.Pow(-1, i) * matrix[0, i] * Determinant(subMatrix);
|
|
}
|
|
|
|
return determinant;
|
|
}
|
|
}
|
|
|
|
|
|
}
|
|
}
|
|
|