Skip to content

Commit b976ea0

Browse files
authored
Merge pull request TheAlgorithms#213 from i-gnasius/hamming_distance
Add hamming_distance algorithm
2 parents 2f6c267 + fcca542 commit b976ea0

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

strings/hamming_distance.rb

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# https://en.wikipedia.org/wiki/Hamming_distance
2+
3+
def hamming_distance(str1, str2)
4+
abort 'Strings must be of the same length' unless str1.length == str2.length
5+
6+
str1.chars.zip(str2.chars).sum { |chr1, chr2| chr1 == chr2 ? 0 : 1 }
7+
end
8+
9+
if $0 == __FILE__
10+
# Valid inputs
11+
puts hamming_distance 'ruby', 'rust'
12+
# => 2
13+
puts hamming_distance 'karolin', 'kathrin'
14+
# => 3
15+
puts hamming_distance 'kathrin', 'kerstin'
16+
# => 4
17+
puts hamming_distance '0000', '1111'
18+
# => 4
19+
20+
# Invalid inputs
21+
puts hamming_distance 'ruby', 'foobar'
22+
# => Strings must be of the same length
23+
end

0 commit comments

Comments
 (0)