We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
2 parents 2f6c267 + fcca542 commit b976ea0Copy full SHA for b976ea0
strings/hamming_distance.rb
@@ -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
19
20
+ # Invalid inputs
21
+ puts hamming_distance 'ruby', 'foobar'
22
+ # => Strings must be of the same length
23
0 commit comments