// Arup Guha
// 4/2/2012
// Written in COT 4500 - Calculates a determinant using
// the recursive definition.

#include <stdio.h>

#define SIZE 10

// Returns the determinant of the n x n matrix det.
double determinant(double det[], int n);

int main() {

    FILE* ifp = fopen("matrix.txt", "r");

    int numcases;
    fscanf(ifp, "%d", &numcases);

    // Go through each case.
    int loop;
    for (loop=1; loop<=numcases; loop++) {

        int n;

        // Read in the size of the determinant.
        fscanf(ifp, "%d", &n);

        double matrix[SIZE*SIZE];

        // Read in the whole matrix.
        int i;
        for (i=0; i<n*n; i++)
            fscanf(ifp, "%lf", &matrix[i]);

        // Print the determinant.
        printf("Case %d: Det is %lf\n", loop, determinant(matrix, n));
    }
    return 0;
}

// Returns the determinant of the n x n matrix det.
double determinant(double det[], int n) {

    // Base case.
    if (n == 1)
        return det[0];

    // Add up each component in the recursive definition, using row 0.
    double sum = 0;
    int i;
    for (i=0; i<n; i++) {

        int index = 0;
        double minor[SIZE*SIZE];
        int j;

        // Copy in all terms for the minor
        for (j=0; j<n*n; j++) {

            // Checks for column or row of minor
            if (j%n == i || j/n == 0)
                continue;

            // If we get here, this is a term in the minor.
            minor[index] = det[j];
            index++;
        }

        // Recursively calculate this determinant.
        double term = determinant(minor, n-1);

        // Since we are on row 0, this is how we test whether or not
        // we add or subtract this term.
        if (i%2 == 0)
            sum = sum + det[i]*term;
        else
            sum = sum - det[i]*term;

    }

    // Here is our answer.
    return sum;
}

