檢查冪等矩陣的JavaScript程式
冪等矩陣是一個方陣,它具有相同數量的行和列,當我們將矩陣自身相乘時,結果將等於相同的矩陣。我們將得到一個矩陣,我們必須找到它是否是冪等矩陣。
數學上−
如果給定的矩陣是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 not
function 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)空間複雜度下工作的程式碼。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP