Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions strings/hamming_distance.rb
Original file line number Diff line number Diff line change
@@ -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 }
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: I think this code can be written a bit shorter as follows:

Suggested change
str1.chars.zip(str2.chars).sum { |chr1, chr2| chr1 == chr2 ? 0 : 1 }
str1.chars.zip(str2.chars).count { |chr1, chr2| chr1 != chr2 }

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