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

การหาตัวอักษรที่ปรากฏบ่อยเป็นอันดับสองใน JavaScript

ภาพรวม

บทความนี้สาธิตวิธีหาตัวอักษรที่มีความถี่เป็นอันดับสองในสตริง

ตัวอย่าง

Input: 'Hello world, I have never seen such a beautiful weather in the world'
Output: 'e'

การนำไปใช้

const secondFrequent = (str) => {
  const map = {};
  for (let i = 0; i < str.length; i++) {
    map[str[i]] = (map[str[i]] || 0) + 1;
  }
  
  const freqArr = Object.entries(map).sort((a, b) => b[1] - a[1]);
  return freqArr[1][0];
};

console.log(secondFrequent('Hello world, I have never seen such a beautiful weather in the world'));

ผลลัพธ์

e

การจัดการ Tie (ค่าความถี่เท่ากัน)

const secondFrequentWithTie = (str) => {
  const freq = [...str].reduce((acc, c) => (acc[c] = (acc[c] || 0) + 1, acc), {});
  
  // จัดกลุ่มตาม Frequency
  const groups = Object.entries(freq).reduce((acc, [char, count]) => {
    (acc[count] = acc[count] || []).push(char);
    return acc;
  }, {});
  
  const sortedFreqs = Object.keys(groups).map(Number).sort((a, b) => b - a);
  
  if (sortedFreqs.length < 2) return null;
  
  // ถ้ามีหลายตัวที่ Frequency เท่ากัน คืนตัวแรก (หรือทั้งหมด)
  return groups[sortedFreqs[1]][0];
};

เวอร์ชัน Unicode-Safe

const secondFrequentUnicode = (str) => {
  const freq = new Map();
  for (const char of str) { // รองรับ Surrogate Pairs
    freq.set(char, (freq.get(char) || 0) + 1);
  }
  
  const sorted = [...freq.entries()].sort((a, b) => b[1] - a[1]);
  return sorted[1]?.[0] ?? null;
};

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

  • Cryptanalysis: Frequency Analysis (คู่กับ Most Frequent)
  • Text Statistics: Character Distribution
  • Compression: Huffman Coding Preparation
  • Language Detection: Character Frequency Profiles

ข้อควรระวัง

  • Space และ Punctuation นับรวมอยู่ด้วย
  • Case Sensitivity: 'H' != 'h'
  • Tie Breaking: ไม่ได้ระบุชัดเจน
  • Empty String / Single Char: คืน null