Tuesday, May 31, 2011

Googling for Code

You need a piece of code to implement a very standard algorithm. You could write it yourself, but instead you Google for it. No need to re-invent the wheel you say to yourself. Then frustration sets in..
My particular need was for a function in C++ to calculate the determinant of a square NxN integer matrix. Ideally I want something non-recursive and which does not need to allocate any memory.

Doesn’t seem like a lot to ask. However the solutions I find are all recursive, some very poorly written, some hundreds of lines long. Many are specific to the trivial 2x2 or 3x3 case. Most allocate a lot of memory from the heap. Now I hate recursion – does my head in - but I had assumed that a recursive algorithm was optional and that a non-recursive alternative always existed. Some websites held out the promise of a solution, but only if I signed up to join some group or other which would probably expose me to requests for payments, annoying ads and a deluge of emails. No thanks.

Anyway my search resulted in failure, so I resorted to writing my own – something which really should not be happening at this stage in the game. It does use recursion, and it allocates a very small amount of memory, but its less than 20 lines long.

int determinant(int n,int *matrix[])
{
     int i,j,k,sign=1,det=0;
     int **minor;
     if (n==1) return matrix[0][0];
     minor=new int* [n-1];
     for (i=0;i<n;i++)
     {
         for (j=k=0;j<n-1;j++)
         {
             if (j==i) k++; // skip i-th row
             minor[j]=&matrix[k++][1];
         }
         det+=sign*matrix[i][0]*determinant(n-1,minor);
         sign=-sign;
     }
     delete [] minor;
     return det;
}

No comments:

Post a Comment