Merge pull request #213 from i-gnasius/hamming_distance

Add hamming_distance algorithm
This commit is contained in:
vzvu3k6k 2024-01-03 22:25:02 +09:00 committed by GitHub
commit b976ea0883
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -0,0 +1,23 @@
# https://en.wikipedia.org/wiki/Hamming_distance
def hamming_distance(str1, str2)
abort 'Strings must be of the same length' unless str1.length == str2.length
str1.chars.zip(str2.chars).sum { |chr1, chr2| chr1 == chr2 ? 0 : 1 }
end
if $0 == __FILE__
# Valid inputs
puts hamming_distance 'ruby', 'rust'
# => 2
puts hamming_distance 'karolin', 'kathrin'
# => 3
puts hamming_distance 'kathrin', 'kerstin'
# => 4
puts hamming_distance '0000', '1111'
# => 4
# Invalid inputs
puts hamming_distance 'ruby', 'foobar'
# => Strings must be of the same length
end