在 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 ] ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP