diff options
author | rsiddharth <s@ricketyspace.net> | 2020-09-04 18:36:19 -0400 |
---|---|---|
committer | rsiddharth <s@ricketyspace.net> | 2020-09-04 18:37:44 -0400 |
commit | 46205268e4984389585a44336f2e1a3804c0ac8d (patch) | |
tree | edbde3b2b011fd216e041e99d184f7213658a1ad /lib | |
parent | 24de922d70b7e71cf1f8415035f8c075ee67e3d0 (diff) |
lib: add HammingDistance
* lib/hamming.go (HammingDistance, setBits): New functions.
Diffstat (limited to 'lib')
-rw-r--r-- | lib/hamming.go | 27 |
1 files changed, 27 insertions, 0 deletions
diff --git a/lib/hamming.go b/lib/hamming.go new file mode 100644 index 0000000..c267c43 --- /dev/null +++ b/lib/hamming.go @@ -0,0 +1,27 @@ +// Copyright © 2020 rsiddharth <s@ricketyspace.net> +// SPDX-License-Identifier: ISC + +package lib + +func HammingDistance(a, b string) int { + if len(a) != len(b) { + return -1 // Fail. + } + + d := 0 + for i := 0; i < len(a); i++ { + c := a[i] ^ b[i] + d += setBits(c) + } + return d +} + +// Returns number of set bits. +func setBits(b byte) int { + var c byte = 0 + for i := 0; i < 8; i++ { + c += b & 0x1 + b = b >> 1 + } + return int(c) +} |