Sha256: 21c343f9e570cd0797edf3ea1d3344ba7a5fb86f5bd254c77e2490613f10f3b6

Contents?: true

Size: 920 Bytes

Versions: 4

Compression:

Stored size: 920 Bytes

Contents

# frozen_string_literal: true

module Edits
  # Implements Hamming distance algorithm
  #
  # @see https://en.wikipedia.org/wiki/Hamming_distance
  module Hamming
    # Calculate the Hamming distance between two sequences.
    #
    # @note A true distance metric, satisfies triangle inequality.
    # @example
    #   Edits::Hamming.distance("explorer", "exploded")
    #   # => 2
    # @param seq1 [String, Array]
    # @param seq2 [String, Array]
    # @return [Integer] distance, 0 (identical) or greater (more distant)
    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
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
edits-0.5.0 lib/edits/hamming.rb
edits-0.4.0 lib/edits/hamming.rb
edits-0.3.0 lib/edits/hamming.rb
edits-0.2.2 lib/edits/hamming.rb