class Hamming

Public Class Methods

distance(a, b) click to toggle source
# File lib/hamming.rb, line 13
def distance(a, b)
  a = a.kind_of?(Array) ? vector_to_hash(a) : a
  b = b.kind_of?(Array) ? vector_to_hash(b) : b

  n = a.hex ^ b.hex

  ones = 0

  while n > 0
    n &= n - 1
    ones += 1
  end

  ones
end
hash_to_vector(hash) click to toggle source
# File lib/hamming.rb, line 9
def hash_to_vector(hash)
  hash.hex.to_s(2).split("").map(&:to_i)
end
vector_to_hash(vector) click to toggle source
# File lib/hamming.rb, line 5
def vector_to_hash(vector)
  vector.join.to_i(2).to_s(16)
end