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

การจับคู่อาร์เรย์จากปลายสองข้าง (Pairing Extremes) ใน JavaScript

ภาพรวม

บทความนี้สาธิตวิธีจับคู่ Element แรกกับตัวสุดท้าย, ตัวที่สองกับตัวสุดท้ายลำดับที่สอง เป็นต้น

ตัวอย่าง

Input:  [1, 2, 3, 4, 5, 6]
Output: [[1, 6], [2, 5], [3, 4]]

Input:  [1, 2, 3, 4, 5] (Odd Length)
Output: [[1, 5], [2, 4], [3]]

การนำไปใช้

const edgePairs = (arr) => {
  const res = [];
  const upto = arr.length % 2 === 0 ? arr.length / 2 : Math.floor(arr.length / 2);
  
  for (let i = 0; i < upto; i++) {
    res.push([arr[i], arr[arr.length - 1 - i]]);
  }
  
  if (arr.length % 2 !== 0) {
    res.push([arr[Math.floor(arr.length / 2)]]);
  }
  return res;
};

console.log(edgePairs([1, 2, 3, 4, 5, 6]));
console.log(edgePairs([1, 2, 3, 4, 5]));

ผลลัพธ์

[ [ 1, 6 ], [ 2, 5 ], [ 3, 4 ] ]
[ [ 1, 5 ], [ 2, 4 ], [ 3 ] ]

วิธีการทันสมัย (Functional)

const edgePairsModern = (arr) => {
  const half = Math.ceil(arr.length / 2);
  return Array.from({ length: half }, (_, i) => 
    i === arr.length - 1 - i 
      ? [arr[i]] 
      : [arr[i], arr[arr.length - 1 - i]]
  );
};

// หรือใช้ Two Pointers
const edgePairsTwoPointer = (arr) => {
  const res = [];
  let left = 0, right = arr.length - 1;
  while (left < right) {
    res.push([arr[left++], arr[right--]]);
  }
  if (left === right) res.push([arr[left]]);
  return res;
};

การประยุกต์ใช้

  • Tournament Brackets: Seeding (1 vs N, 2 vs N-1)
  • Load Balancing: Pair Heavy + Light Tasks
  • Two Sum Problem: Sorted Array Approach
  • Palindrome Checking
  • Divide & Conquer Algorithms

ข้อควรระวัง

  • Original Array ไม่ถูก Mutate (ในเวอร์ชัน Modern)
  • Odd Length: ตัวกลางอยู่คนเดียว
  • Empty Array: คืน []