4.6 KiB
4.6 KiB
title | id | challengeType |
---|---|---|
Jaro distance | 5a23c84252665b21eecc7ec2 | 5 |
Description
- \(m\) is the number of matching characters;
- \(t\) is half the number of transpositions.
- \(m = 4\)
- \(|s_1| = 6\)
- \(|s_2| = 5\)
- \(t = 0\)
Instructions
Tests
tests:
- text: <code>jaro</code> should be a function.
testString: 'assert(typeof jaro=="function","<code>jaro</code> should be a function.");'
- text: <code>jaro(""+tests[0][0]+"",""+tests[0][1]+"")</code> should return a number.
testString: 'assert(typeof jaro(tests[0][0],tests[0][1])=="number","<code>jaro()</code> should return a number.");'
- text: <code>jaro(""+tests[0][0]+"",""+tests[0][1]+"")</code> should return <code>"+results[0]+"</code>.
testString: 'assert.equal(jaro(tests[0][0],tests[0][1]),results[0],"<code>jaro(""+tests[0][0]+"",""+tests[0][1]+"")</code> should return <code>"+results[0]+"</code>.");'
- text: <code>jaro(""+tests[1][0]+"",""+tests[1][1]+"")</code> should return <code>"+results[1]+"</code>.
testString: 'assert.equal(jaro(tests[1][0],tests[1][1]),results[1],"<code>jaro(""+tests[1][0]+"",""+tests[1][1]+"")</code> should return <code>"+results[1]+"</code>.");'
- text: <code>jaro(""+tests[2][0]+"",""+tests[2][1]+"")</code> should return <code>"+results[2]+"</code>.
testString: 'assert.equal(jaro(tests[2][0],tests[2][1]),results[2],"<code>jaro(""+tests[2][0]+"",""+tests[2][1]+"")</code> should return <code>"+results[2]+"</code>.");'
- text: <code>jaro(""+tests[3][0]+"",""+tests[3][1]+"")</code> should return <code>"+results[3]+"</code>.
testString: 'assert.equal(jaro(tests[3][0],tests[3][1]),results[3],"<code>jaro(""+tests[3][0]+"",""+tests[3][1]+"")</code> should return <code>"+results[3]+"</code>.");'
- text: <code>jaro(""+tests[4][0]+"",""+tests[4][1]+"")</code> should return <code>"+results[4]+"</code>.
testString: 'assert.equal(jaro(tests[4][0],tests[4][1]),results[4],"<code>jaro(""+tests[4][0]+"",""+tests[4][1]+"")</code> should return <code>"+results[4]+"</code>.");'
Challenge Seed
function jaro (s, t) {
// Good luck!
}
After Test
console.info('after the test');
Solution
function jaro (s, t) {
var s_len = s.length;
var t_len = t.length;
if (s_len == 0 && t_len == 0) return 1;
var match_distance = Math.max(s_len, t_len) / 2 - 1;
var s_matches = new Array(s_len);
var t_matches = new Array(t_len);
var matches = 0;
var transpositions = 0;
for (var i = 0; i < s_len; i++) {
var start = Math.max(0, i - match_distance);
var end = Math.min(i + match_distance + 1, t_len);
for (var j = start; j < end; j++) {
if (t_matches[j]) continue;
if (s.charAt(i) != t.charAt(j)) continue;
s_matches[i] = true;
t_matches[j] = true;
matches++;
break;
}
}
if (matches == 0) return 0;
var k = 0;
for (var i = 0; i < s_len; i++) {
if (!s_matches[i]) continue;
while (!t_matches[k]) k++;
if (s.charAt(i) != t.charAt(k)) transpositions++;
k++;
}
return ((matches / s_len) +
(matches / t_len) +
((matches - transpositions / 2.0) / matches)) / 3.0;
}