在 JavaScript 中建立特定大小的二進位制螺旋陣列


問題

我們需要編寫一個 JavaScript 函式,該函式接收一個數字 n。我們的函式應該構造並返回 N * N 階(2-D 陣列)的陣列,其中 1 佔據以 [0, 0] 開始的螺旋所有位置,而所有 0 佔據非螺旋位置。

因此,對於 n = 5,輸出如下所示 −

[
   [ 1, 1, 1, 1, 1 ],
   [ 0, 0, 0, 0, 1 ],
   [ 1, 1, 1, 0, 1 ],
   [ 1, 0, 0, 0, 1 ],
   [ 1, 1, 1, 1, 1 ]
]

示例

以下是程式碼 −

 即時演示

const num = 5;
const spiralize = (num = 1) => {
   const arr = [];
   let x, y;
   for (x = 0; x < num; x++) {
      arr[x] = Array.from({
         length: num,
      }).fill(0);
   }
   let left = 0;
   let right = num;
   let top = 0;
   let bottom = num;
   x = left;
   y = top;
   let h = Math.floor(num / 2);
   while (left < right && top < bottom) {
      while (y < right) {
         arr[x][y] = 1;
         y++;
      }
      y--;
      x++;
      top += 2;
      if (top >= bottom) break;
      while (x < bottom) {
         arr[x][y] = 1;
         x++;
      }
      x--;
      y--;
      right -= 2;
      if (left >= right) break;
      while (y >= left) {
         arr[x][y] = 1;
         y--;
      }
      y++;
      x--;
      bottom -= 2;
      if (top >= bottom) break;
      while (x >= top) {
         arr[x][y] = 1;
         x--;
      }
      x++;
      y++;
      left += 2;
   }
   if (num % 2 == 0) arr[h][h] = 1;
   return arr;
};
console.log(spiralize(num));

輸出

以下是控制檯輸出 −

[
   [ 1, 1, 1, 1, 1 ],
   [ 0, 0, 0, 0, 1 ],
   [ 1, 1, 1, 0, 1 ],
   [ 1, 0, 0, 0, 1 ],
   [ 1, 1, 1, 1, 1 ]
]

更新於: 2021 年 4 月 17 日

157 次瀏覽

開啟你的事業

完成課程獲得認證

開始
廣告
© . All rights reserved.