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 ] ]

更新日期: 11-Dec-2020

522 次閱讀

開始您的 職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.