3.4 KiB
3.4 KiB
id | title | challengeType | isHidden |
---|---|---|---|
5e4ce2eaac708cc68c1df260 | Levenshtein distance | 5 | false |
Description
- kitten sitten (substitution of 'k' with 's')
- sitten sittin (substitution of 'e' with 'i')
- sittin sitting (insert 'g' at the end).
Instructions
Tests
tests:
- text: <code>levenshtein</code> should be a function.
testString: assert(typeof levenshtein == 'function');
- text: <code>levenshtein("mist", "dist")</code> should return a number.
testString: assert(typeof levenshtein("mist", "dist") == 'number');
- text: <code>levenshtein("mist", "dist")</code> should return <code>1</code>.
testString: assert.equal(levenshtein("mist", "dist"), 1);
- text: <code>levenshtein("tier", "tor")</code> should return <code>2</code>.
testString: assert.equal(levenshtein("tier", "tor"), 2);
- text: <code>levenshtein("kitten", "sitting")</code> should return <code>3</code>.
testString: assert.equal(levenshtein("kitten", "sitting"), 3);
- text: <code>levenshtein("stop", "tops")</code> should return <code>2</code>.
testString: assert.equal(levenshtein("stop", "tops"), 2);
- text: <code>levenshtein("rosettacode", "raisethysword")</code> should return <code>8</code>.
testString: assert.equal(levenshtein("rosettacode", "raisethysword"), 8);
- text: <code>levenshtein("mississippi", "swiss miss")</code> should return <code>8</code>.
testString: assert.equal(levenshtein("mississippi", "swiss miss"), 8);
Challenge Seed
function levenshtein(a, b) {
// Good luck!
}
Solution
function levenshtein(a, b) {
var t = [], u, i, j, m = a.length, n = b.length;
if (!m) { return n; }
if (!n) { return m; }
for (j = 0; j <= n; j++) { t[j] = j; }
for (i = 1; i <= m; i++) {
for (u = [i], j = 1; j <= n; j++) {
u[j] = a[i - 1] === b[j - 1] ? t[j - 1] : Math.min(t[j - 1], t[j], u[j - 1]) + 1;
} t = u;
} return u[n];
}