ภาพรวม
บทความนี้สาธิตวิธีนับจำนวนตำแหน่งที่ตัวอักษรต่างกันระหว่างสตริงสองตัว (Hamming Distance แบบง่าย) โดยเปรียบเทียบตำแหน่งที่ตรงกัน
ตัวอย่าง
const str1 = 'Hello world!!!';
const str2 = 'Hellp world111';
ตำแหน่งที่ต่างกัน: index 4 (o vs p), 11 (! vs 1), 12 (! vs 1), 13 (! vs 1) = 4 ตำแหน่ง
การนำไปใช้
const dissimilarity = (str1 = '', str2 = '') => {
let count = 0;
const maxLen = Math.max(str1.length, str2.length);
for (let i = 0; i < maxLen; i++) {
if (str1[i] !== str2[i]) {
count++;
}
}
return count;
};
console.log(dissimilarity(str1, str2)); // 4
ผลลัพธ์
4
การปรับปรุง: รองรับสตริงความยาวต่างกัน
โค้ดต้นฉบับลูปแค่ `str1.length` ซึ่งอาจพลาดหาก `str2` ยาวกว่า วิธีที่ดีกว่าคือลูปตามความยาวสูงสุด
วิธีการทันสมัย
// ใช้ spread operator และ reduce
const hammingDistance = (str1, str2) => {
const maxLen = Math.max(str1.length, str2.length);
return [...str1.padEnd(maxLen)].reduce(
(count, char, i) => count + (char !== str2[i] ? 1 : 0),
0
);
};
// หรือใช้ Array.from
const hammingDistance2 = (str1, str2) =>
Array.from({ length: Math.max(str1.length, str2.length) }, (_, i) =>
(str1[i] || '') !== (str2[i] || '')
).filter(Boolean).length;
แนวคิดที่เกี่ยวข้อง
- Hamming Distance: ระยะห่างระหว่างสตริงความยาวเท่ากัน (นับตำแหน่งที่ต่างกัน)
- Levenshtein Distance: ระยะห่างการแก้ไข (Insert, Delete, Substitute)
- Jaro-Winkler Distance: ความคล้ายคลึงของสตริง ใช้ใน fuzzy matching
การประยุกต์ใช้
- Spell Checker / Auto-correct
- DNA Sequence Analysis
- Plagiarism Detection
- Fuzzy Search