refactored hamming distance function