使用 Javascript 翻轉並反轉矩陣
問題
我們需要編寫一個 JavaScript 函式,它以一個 2-D 二進位制陣列 arr(一個僅包含 0 或 1 的陣列)作為第一個也是唯一一個引數。
我們的函式應首先水平翻轉該矩陣,然後將其反轉,並返回結果矩陣。
水平翻轉矩陣意味著矩陣的每一行都將反轉。例如,將 [1, 1, 0] 水平翻轉會得到 [0, 1, 1]。
反轉矩陣意味著將每個 0 替換為 1,將每個 1 替換為 0。例如,反轉 [0, 1, 1] 會得到 [1, 0, 0]。
例如,如果函式的輸入是
輸入
const arr = [ [1, 1, 0], [1, 0, 1], [0, 0, 0] ];
輸出
const output = [ [1,0,0], [0,1,0], [1,1,1] ];
輸出解釋
首先,我們反轉每一行 -
[[0,1,1],[1,0,1],[0,0,0]]
然後,我們反轉該矩陣 -
[[1,0,0],[0,1,0],[1,1,1]]
示例
以下為程式碼 -
const arr = [
[1, 1, 0],
[1, 0, 1],
[0, 0, 0]
];
const flipAndInvert = (arr = []) => {
const invert = n => (n === 1 ? 0 : 1)
for(let i = 0; i < arr.length; i++) {
for(let j = 0; j < arr[i].length / 2; j++) {
const index2 = arr[i].length - 1 - j
if(j === index2) {
arr[i][j] = invert(arr[i][j])
} else {
const temp = arr[i][j]
arr[i][j] = arr[i][index2]
arr[i][index2] = temp
arr[i][j] = invert(arr[i][j])
arr[i][index2] = invert(arr[i][index2])
}
}
}
};
flipAndInvert(arr);
console.log(arr);輸出
[ [ 1, 0, 0 ], [ 0, 1, 0 ], [ 1, 1, 1 ] ]
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP