เราต้องเขียนฟังก์ชัน JavaScript ที่สามารถเปรียบเทียบสตริงสองสตริงและคืนค่าเปอร์เซ็นต์ความคล้ายคลึงของว่าพวกมันคล้ายกันแค่ไหน เปอร์เซ็นต์จะไม่เป็นอะไรนอกจากขนาดของตัวอักษรที่สองสตริงมีร่วมกัน
ถ้าพวกมันคล้ายกันสมบูรณ์ ผลลัพธ์ควรเป็น 100 และถ้าพวกมันไม่มีตัวอักษรร่วมกันเลย ผลลัพธ์ควรเป็น 0
ตัวอย่าง
const calculateSimilarity = (str1 = '', str2 = '') => {
let longer = str1;
let shorter = str2;
if (str1.length < str2.length) {
longer = str2; shorter = str1;
}
let longerLength = longer.length;
if (longerLength == 0) {
return 1.0;
}
return +((longerLength - matchDestructively(longer, shorter)) / parseFloat(longerLength) * 100).toFixed(2);
};
const matchDestructively = (str1 = '', str2 = '') => {
str1 = str1.toLowerCase();
str2 = str2.toLowerCase();
let arr = new Array();
for (let i = 0; i <= str1.length; i++) {
let lastValue = i;
for (let j = 0; j <= str2.length; j++) {
if (i == 0){
arr[j] = j;
}else if(j > 0){
let newValue = arr[j - 1];
if(str1.charAt(i - 1) != str2.charAt(j - 1))
newValue = Math.min(Math.min(newValue, lastValue), arr[j]) + 1;
arr[j - 1] = lastValue; lastValue = newValue;
}
}
if (i > 0) arr[str2.length] = lastValue;
}
return arr[str2.length];
};
console.log(calculateSimilarity('Mathematics','Mathamatecs'));
ผลลัพธ์
สิ่งนี้จะให้ผลลัพธ์ดังนี้:
[ [ 1, 10, 100 ], [ 1, 10, 200 ], [ 1, 10, 300 ], [ 1, 20, 100 ], [ 1, 20, 200 ], [ 1, 20, 300 ], [ 2, 10, 100 ], [ 2, 10, 200 ], [ 2, 10, 300 ], [ 2, 20, 100 ], [ 2, 20, 200 ], [ 2, 20, 300 ] ]