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

การสร้างอาร์เรย์ Mapping ตัวอักษร Unique ในสตริง JavaScript

ภาพรวม

บทความนี้สาธิตวิธี Mapping ตัวอักษรในสตริงเป็นตัวเลข: ตัวอักษรใหม่ (Unique) ได้หมายเลขเพิ่มขึ้น, ตัวซ้ำได้หมายเลขเดิม

ตัวอย่าง

Input:  'heeeyyyy'
Output: [0, 1, 1, 1, 2, 2, 2, 2]
// h->0, e->1, e->1, e->1, y->2, y->2, y->2, y->2

การนำไปใช้

const mapString = (str) => {
  const res = [];
  let curr = '', count = -1;
  
  for (let i = 0; i < str.length; i++) {
    if (str[i] === curr) {
      res.push(count);
    } else {
      count++;
      res.push(count);
      curr = str[i];
    }
  }
  return res;
};

console.log(mapString('heeeyyyy'));

ผลลัพธ์

[0, 1, 1, 1, 2, 2, 2, 2]

หมายเหตุ: โค้ดนี้นับ Consecutive Unique Groups ไม่ใช่ Global Unique

หาก Input: 'ababa' -> Output: [0,1,2,3,4] (เพราะ a,b,a,b,a ล้วนไม่ซ้ำติดกัน)

แตถ้าต้องการ Global Unique Mapping (a->0, b->1 ทุกครั้ง):

Global Unique Mapping

const globalUniqueMap = (str) => {
  const map = new Map();
  let counter = 0;
  return [...str].map(char => {
    if (!map.has(char)) map.set(char, counter++);
    return map.get(char);
  });
};

console.log(globalUniqueMap('heeeyyyy')); // [0, 1, 1, 1, 2, 2, 2, 2] (เหมือนเดิมในกรณีนี้)
console.log(globalUniqueMap('ababa'));    // [0, 1, 0, 1, 0] (ต่างจาก Consecutive)

Run-Length Encoding (RLE) - เกี่ยวข้อง

const runLengthEncode = (str) => {
  const result = [];
  let count = 1;
  for (let i = 1; i <= str.length; i++) {
    if (i < str.length && str[i] === str[i-1]) {
      count++;
    } else {
      result.push([str[i-1], count]);
      count = 1;
    }
  }
  return result;
};

console.log(runLengthEncode('heeeyyyy')); // [['h',1], ['e',3], ['y',4]]

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

  • Data Compression: RLE, Dictionary Coding
  • Pattern Recognition: Sequence Labeling
  • Bioinformatics: DNA Sequence Compression
  • Text Processing: Tokenization