JavaScript 中的方陣旋轉
我們需要編寫一個 JavaScript 函式來接收一個 n * n 階的陣列陣列(方陣)。該函式應將陣列旋轉 90 度(順時針)。條件是,我們必須就地完成此操作(無需分配任何其他陣列)。
例如 −
如果輸入陣列為 −
const arr = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ];
則旋轉後的陣列應如下所示 −
const output = [ [7, 4, 1], [8, 5, 2], [9, 6, 3], ];
示例
以下為程式碼 −
const arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
const rotateArray = (arr = []) => {
for (let rowIndex = 0; rowIndex < arr.length; rowIndex += 1) {
for (let columnIndex = rowIndex + 1; columnIndex < arr.length;
columnIndex += 1) {
[
arr[columnIndex][rowIndex],
arr[rowIndex][columnIndex],
] = [
arr[rowIndex][columnIndex],
arr[columnIndex][rowIndex],
];
}
}
for (let rowIndex = 0; rowIndex < arr.length; rowIndex += 1) {
for (let columnIndex = 0; columnIndex < arr.length / 2;
columnIndex += 1) {
[
arr[rowIndex][arr.length - columnIndex - 1],
arr[rowIndex][columnIndex],
] = [
arr[rowIndex][columnIndex],
arr[rowIndex][arr.length - columnIndex - 1],
];
}
}
};
rotateArray(arr);
console.log(arr);輸出
以下為控制檯上的輸出 −
[ [ 7, 4, 1 ], [ 8, 5, 2 ], [ 9, 6, 3 ] ]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP