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

การหา Element กลางของอาร์เรย์โดยไม่ใช้ Length Property ใน JavaScript

ภาพรวม

บทความนี้สาธิตวิธีหา Element กลางของอาร์เรย์โดยไม่เข้าถึง .length และไม่ใช้ Loop แบบ Built-in (for/while) ใช้ Recursive แทน

การนำไปใช้

const midElement = (arr, ind = 0) => {
  if (arr[ind]) {
    return midElement(arr, ++ind);
  }
  // ind ตอนนี้คือ Length
  return ind % 2 !== 0 
    ? [arr[(ind - 1) / 2]] 
    : [arr[(ind / 2) - 1], arr[ind / 2]];
};

console.log(midElement([14, 32, 36, 42, 45, 66, 87])); // [42] (7 elements)
console.log(midElement([13, 92, 83, 74, 55, 46, 74, 82])); // [74, 55] (8 elements)

ผลลัพธ์

[42]
[74, 55]

วิธีการทั่วไป (ใช้ Length)

const midElementNormal = (arr) => {
  const len = arr.length;
  if (len === 0) return [];
  if (len % 2 === 1) return [arr[Math.floor(len / 2)]];
  return [arr[len / 2 - 1], arr[len / 2]];
};

วิธีการ Functional (ไม่ใช้ Length โดยตรง)

const midElementFunctional = (arr) => {
  const len = arr.reduce((c) => c + 1, 0); // นับความยาว
  const mid = Math.floor(len / 2);
  return len % 2 === 1 ? [arr[mid]] : [arr[mid - 1], arr[mid]];
};

Two Pointers Approach (Iterative, No Length)

const midElementTwoPointers = (arr) => {
  let slow = 0, fast = 0;
  // หา Length ด้วย Fast Pointer
  while (arr[fast] !== undefined) fast++;
  // หรือ Move ทีละ 2 vs 1
  slow = 0; fast = 0;
  while (arr[fast] !== undefined && arr[fast + 1] !== undefined) {
    slow++;
    fast += 2;
  }
  // ตอนนี้ Slow อยู่กลาง (Odd) หรือซ้ายกลาง (Even)
  if (arr[fast] === undefined) { // Even Length
    return [arr[slow - 1], arr[slow]];
  }
  return [arr[slow]]; // Odd Length
};

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

  • Algorithm Practice: Pointer Techniques
  • Linked List Middle Node (Same Concept)
  • Stream Processing: Median of Stream
  • Interview Questions: Constraints-Based Problems

ข้อควรระวัง

  • Recursive: Stack Overflow กับ Array ใหญ่ (>10k elements)
  • Sparse Arrays: arr[ind] === undefined ไม่ได้หมายถึงจบ Array เสมอไป
  • Performance: เข้าถึง .length เร็วกว่ามาก (O(1) vs O(n))