algorith
Version:
Collection complète d'algorithmes de similarité textuelle et moteur de génération aléatoire avancé
28 lines (25 loc) • 710 B
JavaScript
module.exports = function levenshtein(a, b) {
if (a.length === 0 && b.length === 0) return 1;
if (a.length === 0 || b.length === 0) return 0;
const matrix = Array.from({
length: a.length + 1
}, (_, i) =>
Array.from({
length: b.length + 1
}, (_, j) =>
i === 0 ? j : j === 0 ? i : 0
)
);
for (let i = 1; i <= a.length; i++) {
for (let j = 1; j <= b.length; j++) {
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
matrix[i][j] = Math.min(
matrix[i - 1][j] + 1,
matrix[i][j - 1] + 1,
matrix[i - 1][j - 1] + cost
);
}
}
const dist = matrix[a.length][b.length];
return 1 - dist / Math.max(a.length, b.length);
};