Module: Edits::Hamming

Defined in:
lib/edits/hamming.rb

Overview

Implements Hamming distance algorithm

Class Method Summary collapse

Class Method Details

.distance(seq1, seq2) ⇒ Integer

Note:

A true distance metric, satisfies triangle inequality.

Calculate the Hamming distance between two sequences.

Parameters:

  • seq1 (String, Array)
  • seq2 (String, Array)

Returns:

  • (Integer)

    Hamming distance


15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/edits/hamming.rb', line 15

def self.distance(seq1, seq2)
  # if seq1.is_a?(Integer) && seq2.is_a?(Integer)
  #   return (seq1 ^ seq2).to_s(2).count("1")
  # end

  length = seq1.length < seq2.length ? seq1.length : seq2.length
  diff = (seq1.length - seq2.length).abs

  length.times.reduce(diff) do |distance, i|
    seq1[i] == seq2[i] ? distance : distance + 1
  end
end