ปัญหา
เราต้องเขียนฟังก์ชัน JavaScript ที่รับตัวเลข n ฟังก์ชันควรสร้างและคืนค่าอาร์เรย์แบบ 2 มิติ ขนาด N×N โดยที่ 1 จะอยู่ในตำแหน่งที่เกลียว (spiral) เริ่มจาก [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 ]
]