JavaScriptで特定のサイズのバイナリスパイラル配列を作成する
問題
数値nを受け取るJavaScript関数を作成する必要があります。この関数は、N * N次の配列(2次元配列)を作成して返す必要があります。この配列では、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 ] ]
-
JavaScript配列slice()
JavaScriptのslice()メソッドは、配列内の選択された要素を返すために使用されます。 構文は次のとおりです- array.slice(start, end) 上記のstartパラメータは、選択を開始する場所を指定する整数ですが、endは選択が終了する場所です。 JavaScriptでslice()メソッドを実装しましょう- 例 <!DOCTYPE html> <html> <body> <h2>Demo Heading</h2> <p id="t
-
新しいキーワードでJavaScript配列を作成します。
以下は、新しいキーワードを使用してJavaScript配列を作成するためのコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style&