Module: Measurable::Hamming
- Included in:
- Measurable
- Defined in:
- lib/measurable/hamming.rb
Instance Method Summary collapse
-
#hamming(s1, s2) ⇒ Object
call-seq: hamming(s1, s2) -> Integer.
Instance Method Details
#hamming(s1, s2) ⇒ Object
call-seq:
hamming(s1, s2) -> Integer
Count the number of different characters between strings s1
and s2
, that is, how many substitutions are necessary to change s1
into s2
and vice-versa.
See: en.wikipedia.org/wiki/Hamming_distance
-
Arguments :
-
s1
-> A String. -
s2
-> A String with the same size ofs1
.
-
-
Returns :
-
The number of characters in which
s1
ands2
differ.
-
-
Raises :
-
ArgumentError
-> The sizes ofs1
ands2
don’t match.
-
21 22 23 24 25 26 27 28 29 |
# File 'lib/measurable/hamming.rb', line 21 def hamming(s1, s2) # TODO: Change this to a more specific, custom-made exception. raise ArgumentError if s1.size != s2.size s1.chars.zip(s2.chars).reduce(0) do |acc, c| acc += 1 if c[0] != c[1] acc end end |