matrix determinant
GolfScript, 58 chars
n%{~]}%{[.!{(.,,0\{:^2$=-1^?*3${.^<\^)>+}%d*+}/}or])\;}:d~
A straightforward recursive algorithm using Laplace expansion.
Example input (random 5 × 5 matrix):
-562 40 43 -586 347
-229 177 305 -367 50
-434 343 241 -365 -86
-3 -384 -351 61 -214
-400 96 -339 25 -116
Output: 282416596900
(Online demo; Verify with Wolfram Alpha)
The code consists of three parts:
n%{~]}%
parses the input,{[.!{(.,,0\{:^2$=-1^?*3${.^<\^)>+}%d*+}/}or])\;}:d
defines a recursive subroutine to calculate the determinant, and- the final
~
applies the subroutine to the input.
I'm sure there's room for improvement in this code, but at least I beat Gareth by three chars. Also, {:^2$=
is a pretty nice GS smiley. :)
Haskell, 139 131
(a:r)%0=r;(a:r)%n=a:r%(n-1)
d[]=1;d(f:r)=foldr(\(j,x)->(x*d(map(%j)r)-))0$zip[0..]f
main=interact$show.d.map(map read.words).lines
Python 233
def d(x):
l=len(x)
if l<2:return x[0][0]
return sum([(-1)**i*x[i][0]*d(m(x,i))for i in range(l)])
def m(x,i):y=x[:];del(y[i]);y=zip(*y);del(y[0]);return zip(*y)
x=[input()]
for i in (len(x[0])-1)*[1]:x+=[input()]
print d(x)
Ungolfed:
def det(x):
l = len(x)
if l == 1:
return x[0][0]
return sum([(-1)**i*x[i][0]*det(minor(x,i+1,1)) for i in range(l)])
def minor(x,i,j):
y = x[:]
del(y[i-1])
y=zip(*y)
del(y[j-1])
return zip(*y)
def main():
x = [input()]
for i in range(len(x[0])-1):
x += [input()]
print det(x)
if __name__ == '__main__':
main()
Usage
As requested, input is on stdin and output is to stdout.
I interpreted columns separated by any space char to mean that I can use comma delimited numbers. If this is not the case, I will rework my solution.
This could be about 30 characters shorter if I could specify my input matrix in the form [[a,b,c],[d,e,f],[g,h,i]].
./det.py
1,-4,9
-6,7,3
1,2,3
Result
-240
The determinant is found using Laplace Expansion