Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

เกลียวสมาชิกของเมทริกซ์สี่เหลี่ยมจัตุรัสใน JavaScript

เราต้องเขียนฟังก์ชัน 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
]