Search code examples
c#recursionmatrixmultidimensional-arraydeterminants

Computing Array Determinant for NxN Recursive C#


Well, this is giving me a real headache. I'm building a matrix determinant function to compute NxN determinant, and I'm using recursion. The logic is working right but I'm not able to get the final value computed correctly.

Here is my code for Matrix Determinant:

 public static double determinant(double[,]array){
            double det=0;
            double total = 0;
            double[,] tempArr = new double[array.GetLength(0) - 1, array.GetLength(1) - 1];

            if(array.GetLength(0)==2)
            {
                det = array[0, 0] * array[1, 1] - array[0, 1] * array[1, 0];
            }

            else { 

                for (int i = 0; i <1; i++)
                {
                    for (int j = 0; j < array.GetLength(1); j++)
                    {
                        if (j % 2 != 0) array[i, j] = array[i, j] * -1;
                       tempArr= fillNewArr(array, i, j);
                       det+=determinant(tempArr);
                       total =total + (det * array[i, j]);
                    }
                }
                 }
            return det;
        }

and about fillNewArr method it's just a method to trim the array, method is as follow: p

ublic static double[,] fillNewArr(double[,] originalArr, int row, int col)
        {
            double[,] tempArray = new double[originalArr.GetLength(0) - 1, originalArr.GetLength(1) - 1];

            for (int i = 0, newRow = 0; i < originalArr.GetLength(0); i++)
            {
                if (i == row)
                    continue;
                for (int j = 0, newCol=0; j < originalArr.GetLength(1); j++)
                {
                    if ( j == col) continue;
                    tempArray[newRow, newCol] = originalArr[i, j];

                    newCol++;
                }
                newRow++;
            }
            return tempArray;

        }

The method is working as it supposed to "I assume" but the final result is not computed in the right way, why would that be?!

4x4 Array Example:

{2 6 6 2}
{2 7 3 6}
{1 5 0 1}
{3 7 0 7}

Final result should be -168, while mine is 104!


Solution

  • This bit

    if (j % 2 != 0) array[i, j] = array[i, j] * -1;
    tempArr= fillNewArr(array, i, j);
    det+=determinant(tempArr);
    total =total + (det * array[i, j]);
    

    uses a variable total that is never used again. It should probably be something like

    double subdet = determinant(fillNewArr(array, i, j));
    if (j % 2 != 0) subdet *= -1;
    det += array[i, j] * subdet;