-
#!/usr/bin/env lua
-
-
-- This is the constructor of a determinant
-
-- It get an array of numbers as argument
-
-- And add methods for it
-
function Determinant(data)
-
local det={}
-
det.row=math.sqrt(table.maxn(data))
-
-
-- If the number is not proper, raise error
-
if math.floor (det.row) ~= det.row then
-
error("Determinant's data number must be n^2!")
-
end
-
-
det.data=data
-
-
-- index function
-
det.at=function(this,row,column)
-
return this.data[(row-1)*this.row+column];
-
end
-
-
det.cofactor=function(this,row,column)
-
local cofactor={}
-
local r=1
-
local c=0
-
for _,v in ipairs(this.data) do
-
c=c+1;
-
-
if c==this.row+1 then
-
r=r+1
-
c=1
-
end
-
-
if not (r==row or c==column) then
-
table.insert(cofactor,v)
-
end
-
end
-
-
return cofactor
-
end
-
-
-- evaluation function
-
det.eval=function(this)
-
local a=this.data
-
-- this is the simplest case
-
if this.row==2 then
-
return a[1]*a[4]-a[2]*a[3]
-
-
-- for accerleration
-
elseif this.row==3 then
-
return a[1]*a[5]*a[9]+a[3]*a[4]*a[8]+a[2]*a[6]*a[7]-a[3]*a[5]*a[7]-a[1]*a[6]*a[8]-a[2]*a[4]*a[9]
-
else
-
local value=0
-
local cofactor=0
-
local add=true
-
-
for i=1,this.row do
-
cofactor=Determinant(this:cofactor(1,i))
-
cofactor=this.data[i]*cofactor:eval()
-
-
if add then
-
value=value+cofactor
-
else
-
value=value-cofactor
-
end
-
add = not add
-
end
-
-
return value
-
end
-
end
-
-
return det
-
end
-
-