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

การหาความห่างจากสระที่ใกล้ที่สุดในสตริง (Vowel Distance) ใน JavaScript

ภาพรวม

บทความนี้สาธิตวิธีสร้างอาร์เรย์ที่แต่ละตำแหน่งเก็บระยะห่างจากสระ (Vowel: a, e, i, o, u) ที่ใกล้ที่สุด เช่น 'vatghvf' -> [1, 0, 1, 2, 3, 4, 5]

ตัวอย่าง

Input:  'vatghvf'
Index:   0 1 2 3 4 5 6
Char:    v a t g h v f
Vowel:     ^
Distance: 1 0 1 2 3 4 5

การนำไปใช้

const nearest = (arr, el) => 
  arr.reduce((acc, val) => Math.min(acc, Math.abs(val - el)), Infinity);

const vowelNearestDistance = (str = '') => {
  const s = str.toLowerCase();
  const vowelIndex = [];
  
  // หาตำแหน่งสระทั้งหมด
  for (let i = 0; i < s.length; i++) {
    if ('aeiou'.includes(s[i])) {
      vowelIndex.push(i);
    }
  }
  
  // คำนวณระยะห่างสำหรับแต่ละตำแหน่ง
  return [...s].map((_, ind) => nearest(vowelIndex, ind));
};

console.log(vowelNearestDistance('vatghvf'));

ผลลัพธ์

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

วิธีการที่มีประสิทธิภาพมากกว่า (Two Pass O(n))

const vowelDistanceOptimized = (str) => {
  const s = str.toLowerCase();
  const n = s.length;
  const res = new Array(n).fill(Infinity);
  const vowels = new Set('aeiou');
  
  // Pass 1: Left to Right
  let lastVowel = -Infinity;
  for (let i = 0; i < n; i++) {
    if (vowels.has(s[i])) lastVowel = i;
    res[i] = i - lastVowel;
  }
  
  // Pass 2: Right to Left
  lastVowel = Infinity;
  for (let i = n - 1; i >= 0; i--) {
    if (vowels.has(s[i])) lastVowel = i;
    res[i] = Math.min(res[i], lastVowel - i);
  }
  
  return res;
};

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

  • Text Analysis: ความหนาแน่นของสระ
  • Linguistics: โครงสร้างพยางค์ (Syllable Structure)
  • Speech Synthesis: Prosody Modeling
  • Word Games: Scrabble Helper, Crossword Solver
  • DNA Analysis: หา Motif Sites (คล้ายหา Pattern)

ขยายเป็น Consonant Distance

const nearestCharDistance = (str, targetChars) => {
  const targets = new Set(targetChars);
  const n = str.length;
  const res = new Array(n).fill(Infinity);
  
  let last = -Infinity;
  for (let i = 0; i < n; i++) {
    if (targets.has(str[i])) last = i;
    res[i] = i - last;
  }
  
  last = Infinity;
  for (let i = n - 1; i >= 0; i--) {
    if (targets.has(str[i])) last = i;
    res[i] = Math.min(res[i], last - i);
  }
  
  return res;
};