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