Skip to content

Commit 0a2e099

Browse files
committed
inital
0 parents  commit 0a2e099

File tree

10 files changed

+248
-0
lines changed

10 files changed

+248
-0
lines changed

.gitignore

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
/doc/
2+
/lib/
3+
/bin/
4+
/.shards/
5+
.idea/
6+
*.dwarf
7+
8+
# Libraries don't need dependency lock
9+
# Dependencies will be locked in application that uses them
10+
/shard.lock
11+
12+
*.editorconfig

.travis.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
language: crystal

LICENSE

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
The MIT License (MIT)
2+
3+
Copyright (c) 2018 Meyer Lobl
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in
13+
all copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21+
THE SOFTWARE.

README.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# string-metrics
2+
3+
Ports some popular string algorithms for Crystal:
4+
* [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance)
5+
* [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance)
6+
* [Damerau–Levenshtein distance](https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance)
7+
8+
## Installation
9+
10+
Add this to your application's `shard.yml`:
11+
12+
```yaml
13+
dependencies:
14+
string-metrics:
15+
github: mlobl/string-metrics
16+
```
17+
18+
## Usage
19+
20+
```crystal
21+
require "string-metrics"
22+
```
23+
24+
TODO: Write usage instructions here
25+
26+
## Development
27+
28+
TODO: Write development instructions here
29+
30+
## Contributing
31+
32+
1. Fork it ( https://github.com/mlobl/string-metrics/fork )
33+
2. Create your feature branch (git checkout -b my-new-feature)
34+
3. Commit your changes (git commit -am 'Add some feature')
35+
4. Push to the branch (git push origin my-new-feature)
36+
5. Create a new Pull Request
37+
38+
## Contributors
39+
40+
- [mlobl](https://github.com/mlobl) Meyer Lobl - creator, maintainer

benchmark_profiling/levenshtein.cr

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
require "../src/string-metrics"
2+
3+
# A stress test to profile with
4+
a = "n information theory, linguistics and computer science, the Levenshtein distance is a string metric for measuring the difference between two sequences. Informally, the Levenshtein distance between two words is the minimum number of single-character edits (insertions, deletions or substitutions) required to change one word into the other. It is named after the Soviet mathematician Vladimir Levenshtein, who considered this distance in 1965"
5+
b = "The Levenshtein distance can also be computed between two longer strings, but the cost to compute it, which is roughly proportional to the product of the two string lengths, makes this impractical. Thus, when used to aid in fuzzy string searching in applications such as record linkage, the compared strings are usually short to help improve speed of comparisons."
6+
start_time = Time.now()
7+
result = StringMetrics.levenshtein(a*50, b*50)
8+
timing = (Time.now() - start_time)
9+
puts "Distance was #{result} and took #{timing}"

shard.yml

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
name: string-metrics
2+
version: 0.1.0
3+
4+
authors:
5+
- Meyer Lobl <[email protected]>
6+
7+
crystal: 0.24.1
8+
9+
license: MIT

spec/spec_helper.cr

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
require "spec"
2+
require "../src/string-metrics"

spec/string-metrics_spec.cr

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
require "./spec_helper"
2+
3+
describe "StringMetrics" do
4+
it "levenshtein both empty" do
5+
StringMetrics.levenshtein("", "").should eq(0)
6+
end
7+
8+
it "levenshtein one empty" do
9+
StringMetrics.levenshtein("", "hi").should eq(2)
10+
end
11+
12+
it "levenshtein one missing" do
13+
StringMetrics.levenshtein("h", "hi").should eq(1)
14+
end
15+
16+
it "levenshtein one sub" do
17+
StringMetrics.levenshtein("ha", "hi").should eq(1)
18+
end
19+
20+
it "levenshtein one deletion" do
21+
StringMetrics.levenshtein("hai", "hi").should eq(1)
22+
end
23+
24+
it "levenshtein multiple insertions" do
25+
StringMetrics.levenshtein("char", "charity").should eq(3)
26+
end
27+
28+
it "levenshtein multiple insertions and one substitution" do
29+
StringMetrics.levenshtein("char", "sharity").should eq(4)
30+
end
31+
32+
it "levenshtein with many operations" do
33+
StringMetrics.levenshtein("example", "samples").should eq(3)
34+
StringMetrics.levenshtein("sturgeon", "urgently").should eq(6)
35+
StringMetrics.levenshtein("levenshtein", "frankenstein").should eq(6)
36+
StringMetrics.levenshtein("distance", "difference").should eq(5)
37+
end
38+
39+
it "hamming with differing length strings" do
40+
StringMetrics.hamming("hi", "ha").should eq(1)
41+
end
42+
43+
it "hamming with empty strings" do
44+
StringMetrics.hamming("", "").should eq(0)
45+
end
46+
47+
it "hamming with differing length strings" do
48+
expect_raises ArgumentError, do
49+
StringMetrics.hamming("", "check")
50+
end
51+
end
52+
53+
it "damerau levenshtein" do
54+
StringMetrics.damerau_levenshtein("char", "hcra").should eq(2)
55+
end
56+
57+
it "empty strings damerau" do
58+
StringMetrics.damerau_levenshtein("", "").should eq(0)
59+
end
60+
end

src/string-metrics.cr

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
require "./string-metrics/*"
2+
3+
# TODO: Write documentation for `String::Metrics`
4+
module StringMetrics
5+
6+
# Gets the min edit distance between two strings.
7+
# See https://en.wikipedia.org/wiki/Levenshtein_distance
8+
# Ported from https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Python
9+
def self.levenshtein(s1 : String, s2 : String) : Int
10+
return levenshtein(s2, s1) if s1.size < s2.size
11+
return s1.size if s2.size == 0
12+
13+
previous_row = (0..s2.size).to_a
14+
s1_chars = s1.chars
15+
s2_chars = s2.chars
16+
# it's expensive to continually recreate an array
17+
cache = [[0] * (s2.size + 1), [0] * (s2.size + 1)]
18+
s1_chars.each_with_index do |c1, i|
19+
current_row = cache[i % 2]
20+
current_row[0] = i + 1
21+
s2_chars.each_with_index do |c2, j|
22+
insertions = previous_row.unsafe_at(j + 1) + 1
23+
deletions = current_row.unsafe_at(j) + 1
24+
substitutions = previous_row.unsafe_at(j)
25+
substitutions += 1 if c1 != c2
26+
# could have minned a tuple, but this is a bit faster
27+
min = insertions
28+
min = deletions if deletions < min
29+
min = substitutions if substitutions < min
30+
# main bottleneck is here, memory writes to an already allocated address :/
31+
current_row[j + 1] = min
32+
end
33+
previous_row = current_row
34+
end
35+
previous_row.last
36+
end
37+
38+
def self.hamming(s1 : String, s2 : String) : Int
39+
raise ArgumentError.new("input lengths are not equal") if s1.size != s2.size
40+
(0...s2.size).sum { |i| (s1[i] != s2[i])? 1 : 0 }
41+
end
42+
43+
# A variation of the Levenshtein distance, this counts transpositions as a single edit.
44+
# ```damerau_levenshtein("char", "hcar") == 1``` as opposed to a distance of 2 from levenshtein
45+
# on it's own
46+
# Ported from https://github.com/jamesturk/jellyfish/blob/master/jellyfish/_jellyfish.py
47+
def self.damerau_levenshtein(s1 : String, s2 : String) : Int
48+
infinite = s1.size + s2.size
49+
50+
da = Hash(Char, Int32).new(default_value=0)
51+
52+
# distance matrix
53+
score = (0...s1.size + 2).to_a.map {|i| [0]*(s2.size + 2)}
54+
score[0][0] = infinite
55+
56+
(0...s1.size + 1).each do |i|
57+
score[i + 1][0] = infinite
58+
score[i + 1][1] = i
59+
end
60+
(0...s2.size + 1).each do |i|
61+
score[0][i + 1] = infinite
62+
score[1][i + 1] = i
63+
end
64+
65+
s1_chars = s1.chars
66+
s2_chars = s2.chars
67+
68+
(1..s1.size).each do |i|
69+
db = 0
70+
(1..s2.size).each do |j|
71+
i1 = da[s2_chars[j-1]]
72+
j1 = db
73+
cost = 1
74+
if s1_chars[i - 1] == s2_chars[j - 1]
75+
cost = 0
76+
db = j
77+
end
78+
79+
score[i + 1][j + 1] = {
80+
score[i][j] + cost,
81+
score[i+1][j] + 1,
82+
score[i][j+1] + 1,
83+
score[i1][j1] + (i - i1 - 1) + 1 + (j - j1 - 1)
84+
}.min
85+
end
86+
da[s1_chars[i - 1]] = i
87+
end
88+
score[s1.size + 1][s2.size + 1]
89+
end
90+
91+
end

src/string-metrics/version.cr

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module StringMetrics
2+
VERSION = "0.1.0"
3+
end

0 commit comments

Comments
 (0)