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
|
void Main()
{
var myMatrix =new double[]{1,0,2,0,3,0,4,0,5};
CalculDeterminant(myMatrix);
}
double CalculDeterminant(double[] matrice)
{
if(Math.Sqrt(matrice.Length) - Math.Truncate(Math.Sqrt(matrice.Length))>0)
throw new ArgumentException("Matrix is not squared");
if(matrice.Length < 4)
{
throw new ArgumentException("Matrix must be at least 2*2");
}
else if(matrice.Length == 4)
{
return matrice[0] * matrice[3] - matrice[1] * matrice[2];
}
else
{
double acc = 0;
var dim = Convert.ToInt32(Math.Sqrt(matrice.Length));
int i = 0;
foreach(var j in matrice.Take(dim))
{
var vals = Enumerable.Range(0, matrice.Length)
.Skip(dim)
.Except(Enumerable.Range(0, dim - 1).Select (e => (e + 1) * dim + i))
.Select(e=>matrice[e])
.ToArray();
acc += j * (((i % 2) == 0) ? 1 : -1) * CalculDeterminant(vals);
i++;
}
return acc;
}
} |
Partager