เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่ใช้อาร์เรย์อาร์เรย์ของตัวอักษรแบบสองมิติ (จำเป็นต้องมีเมทริกซ์สี่เหลี่ยมจัตุรัส) แบบนี้ -
const arr = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ];
ฟังก์ชันควรสร้างอาร์เรย์ใหม่ที่นำองค์ประกอบแบบเกลียวจากอาร์เรย์อินพุตโดยเริ่มจากตำแหน่ง (0, 0) และส่งคืนอาร์เรย์มิติเดียวนั้น
ดังนั้น สำหรับอาร์เรย์นี้ เกลียวควรมีลักษณะดังนี้ −
const output = [1, 2, 3, 6, 9, 8, 7, 4, 5];
เราจะสร้างตัวแปรชั่วคราวที่ชี้ไปที่แถวปัจจุบันและคอลัมน์ปัจจุบันทั้งที่จุดเริ่มต้นและจุดสิ้นสุด
ด้วยวิธีนี้ เราสามารถเพิ่มแถวเริ่มต้นและคอลัมน์เริ่มต้นซ้ำได้ และลดแถวสิ้นสุดและคอลัมน์สิ้นสุดในลักษณะที่หมุนวนไปทางกึ่งกลางของเมทริกซ์
ตัวอย่าง
const arr = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ];
const spiral = (arr = []) => {
if (!arr || arr.length === 0) {
return [];
};
let startRow = 0;
let startCol = 0;
let res = [];
let endCol = arr[0].length - 1;
let endRow = arr.length - 1;
while (startRow <= endRow && startCol <= endCol) {
for (let i = startCol; i <= endCol; i++) {
res.push(arr[startRow][i]);
}
startRow++;
for (let i = startRow; i <= endRow; i++) {
res.push(arr[i][endCol]);
}
endCol--;
if (startRow <= endRow) {
for (let i = endCol; i >= startCol; i--) {
res.push(arr[endRow][i]);
}
endRow--;
}
if (startCol <= endCol) {
for (let i = endRow; i >= startRow; i--) {
res.push(arr[i][startCol]);
} startCol++;
}
}
return res;
};
console.log(spiral(arr)); ผลลัพธ์
และผลลัพธ์ในคอนโซลจะเป็น −
[ 1, 2, 3, 6, 9, 8, 7, 4, 5 ]