我有一个计算矩阵行列式的递归函数,但在它的参数中我有一个类名,后来我使用该函数,但这次我需要而不是作为类名的参数,我需要它只是一个矩阵的名称。
或者我可以以某种方式在我的较小矩阵中添加一个类吗?或者我该如何欺骗这个。将不胜感激。
function create2Darray(clname)
{
//creates a 2d array of an array returned by the function getElementsByClassName;
var A = document.getElementsByClassName(clname);
var arr = new Array();
var rows = Math.sqrt(A.length);
for(var i = 0;i < rows; i++)
{
arr[i] = new Array();
for(var j = 0; j < rows;j++)
{
arr[i][j] = A[i*rows + j].value;
}
}
return arr;
}
function determinant (matrixClass)
{
var matrix = create2Darray(matrixClass);
var det = 0;
if(matrix.length == 1)
{
return matrix[0][0];
}
else if(matrix.length == 2)
{
return (matrix[0][0] * matrix[1][1]) - (matrix[0][1] * matrix[1][0]);
}
var smaller = new Array();//creating an empty array for a matrix minor;
for(var k = 0;k < matrix.length; k++)
{
smaller[k] = [];
for(var l = 0;l < matrix.length; l++)
{
smaller[k][l] = [];
}
}
for(var i = 0;i < matrix.length; i++)
{
for (a = 1; a < matrix.length; a++)
{
for (b = 0; b < matrix.length; b++)
{
if (b < i)
{
smaller[a - 1][b] = A[a][b];
}
else if (b > i)
{
smaller[a - 1][b - 1] = A[a][b];
}
}
}
if (i % 2 == 0)
s = 1;
else
s = -1;
det += s * A[0][i] * (determinant(smaller));
}
return (det);
alert(det);
}