Skip to content

Commit 7437de8

Browse files
committed
Merge pull request coffeescript-cookbook#69 from BlackTea1988/master
fix bug
2 parents 011ef15 + 19d514d commit 7437de8

File tree

1 file changed

+42
-45
lines changed

1 file changed

+42
-45
lines changed
Lines changed: 42 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,42 @@
1-
---
2-
layout: recipe
3-
title: Matching Strings
4-
chapter: Strings
5-
---
6-
## Problem
7-
8-
You want to match two or more strings.
9-
10-
## Solution
11-
12-
Calculate the edit distance, or number of operations required to transform one string into the other.
13-
14-
{% highlight coffeescript %}
15-
16-
Levenshtein =
17-
(str1, str2) ->
18-
19-
l1 = str1.length
20-
l2 = str2.length
21-
22-
Math.max l1, l2 if Math.min l1, l2 == 0
23-
24-
i = 0; j = 0; distance = []
25-
26-
for i in [0...l1 + 1]
27-
distance[i] = []
28-
distance[i][0] = i
29-
30-
distance[0][j] = j for j in [0...l2 + 1]
31-
32-
for i in [1...l1 + 1]
33-
for j in [1...l2 + 1]
34-
distance[i][j] = Math.min distance[i - 1][j] + 1,
35-
distance[i][j - 1] + 1,
36-
distance[i - 1][j - 1] +
37-
if (str1.charAt i - 1) == (str2.charAt j - 1) then 0 else 1
38-
39-
distance[l1][l2]
40-
41-
{% endhighlight %}
42-
43-
## Discussion
44-
45-
You can use either Hirschberg or Wagner–Fischer's algorithm to calculate a Levenshtein distance. This example uses Wagner–Fischer's algorithm.
1+
---
2+
layout: recipe
3+
title: Matching Strings
4+
chapter: Strings
5+
---
6+
## Problem
7+
8+
You want to match two or more strings.
9+
10+
## Solution
11+
12+
Calculate the edit distance, or number of operations required to transform one string into the other.
13+
14+
{% highlight coffeescript %}
15+
16+
Levenshtein =
17+
(str1, str2) ->
18+
19+
l1 = str1.length
20+
l2 = str2.length
21+
22+
return Math.max l1, l2 unless l1 and l2
23+
24+
i = 0; j = 0; distance = []
25+
26+
distance[i] = [i] for i in [0..l1]
27+
distance[0][j] = j for j in [0..l2]
28+
29+
for i in [1..l1]
30+
for j in [1..l2]
31+
distance[i][j] = Math.min distance[i - 1][j] + 1,
32+
distance[i][j - 1] + 1,
33+
distance[i - 1][j - 1] +
34+
if (str1.charAt i - 1) is (str2.charAt j - 1) then 0 else 1
35+
36+
distance[l1][l2]
37+
38+
{% endhighlight %}
39+
40+
## Discussion
41+
42+
You can use either Hirschberg or Wagner–Fischer's algorithm to calculate a Levenshtein distance. This example uses Wagner–Fischer's algorithm.

0 commit comments

Comments
 (0)