您好,欢迎访问一九零五行业门户网

JavaScript 程序检查幂等矩阵

幂等矩阵是具有相同行数和列数的方阵,当我们将矩阵与其自身相乘时,结果将等于同一个矩阵。我们将得到一个矩阵,我们必须确定它是否是幂等矩阵。
数学上−
如果给定矩阵 ix m,则 m 是幂等矩阵,应遵循以下性质 -
m*m = m
矩阵乘法一个矩阵与另一个矩阵相乘会产生另一个矩阵,如果给定矩阵是 n*n 的方阵,则所得矩阵也将具有相同的维度 (n*n)。
两个矩阵a和b相乘的结果矩阵的每个索引(i,j)是矩阵a的第j列与矩阵b的第i列的乘法之和。
输入mat = [ [1, 0], [0, 1]]
输出yes, the given matrix is an idempotent matrix.
说明for the cell (0,0): we have to multiply [1,0] with [1,0] => 1* 1 + 0 * 0 = 1. for the cell (0,1): we have to multiply [0,1] with [1,0] => 0* 1 + 0 * 1 = 0. for the cell (1,0): we have to multiply [1,0] with [0,1] => 1* 0 + 0 * 1 = 0.for the cell (1,1): we have to multiply [0,1] with [0,1] => 0* 0 + 1 * 1 = 1. so, the final matrix we will get is: [ [1, 0], [0, 1]]
方法我们已经了解了求两个矩阵相乘的示例和方法,现在让我们看看实现代码以求给定矩阵是否为幂等矩阵的步骤。
首先,我们将创建一个函数,该函数将采用单个参数,该参数将作为要查找的矩阵,无论它是否是幂等矩阵。
我们将获取矩阵的长度,并使用它通过 for 循环遍历矩阵的每个单元格。
在每个索引或单元格中,我们将使用上述步骤获取答案矩阵当前单元格中存在的值。
我们将使用for循环遍历当前列和行并得到它们的乘法和。
如果当前总和等于当前索引值,则我们将移至下一个值,否则将返回 false。
根据返回值,打印当前矩阵是否幂等的语句。
示例// function to check if the current matrix is an idempotent matrix or notfunction check(mat){ // getting the size of the given matrix. var n = mat.length; // traversing over the given matrix for(var i = 0;i < n; i++){ for(var j = 0; j<n; j++){ // for the current cell calculating the value present in the resultant matrix // variable to store the current cell value var cur = 0; for(var k = 0; k<n; k++){ cur += mat[k][j]*mat[i][k]; } // if the current value is not equal to value we got for this cell then return false if(cur != mat[i][j]){ return false; } } } // returing true as all the values matched return true;}// defining the matrix var mat = [[2, -2, -4], [-1, 3, 4 ], [1, -2, -3]]console.log(the given matrix is: )console.log(mat);// calling the function to check if the current matrix is idempotent matrix or not if(check(mat)){ console.log(the given matrix is idempotent matrix)}else { console.log(the given matrix is not idempotent matrix)}
时间和空间复杂度上述代码的时间复杂度为 o(n^3),其中 n 是给定矩阵的行数。对于每个单元格,我们必须将当前列与当前行相乘以产生因子或 n,总共有 n^n 个单元格。
上述代码的空间复杂度为 o(1),因为我们没有使用任何额外的空间来存储矩阵。
结论在本教程中,我们实现了一个 javascript 程序来检查给定矩阵是否是幂等矩阵。幂等矩阵是具有相同行数和列数的方阵,当我们将矩阵与其自身相乘时,结果将等于同一个矩阵。我们以 o(n^3) 时间复杂度实现代码,并以 o(1) 空间复杂度工作。
以上就是javascript 程序检查幂等矩阵的详细内容。
其它类似信息

推荐信息