From b28784b5890d5fdc7cd9d4b9bd05d497e19ca6cb Mon Sep 17 00:00:00 2001 From: rsiddharth Date: Sat, 5 Sep 2020 10:40:42 -0400 Subject: lib: add KeySizeWithMinDistance * lib/hamming.go (KeySizeWithMinDistance): New function. --- lib/hamming.go | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) (limited to 'lib/hamming.go') diff --git a/lib/hamming.go b/lib/hamming.go index 1e53d54..05a7546 100644 --- a/lib/hamming.go +++ b/lib/hamming.go @@ -32,6 +32,29 @@ func setBits(b byte) int { return int(c) } + +// Returns key size with minimum normalized hamming distance +// 'keyMin' is the minimum key size +// 'keyMax' is the maximum key size +func KeySizeWithMinDistance(keyMin, keyMax int) int { + var mk int = 0 // Key size with min distance. + var md float64 = 100.0 // Distance for key size 'mk'. + for k := keyMin; k <= keyMax; k++ { + p := genKey(k) + q := genKey(k) + + // Compute distance. + d := HammingDistance(p, q) + + nd := float64(d) / float64(k) + if nd < md { + mk = k + md = nd + } + } + return mk +} + // Generates a key of size 'size' bytes. func genKey(size int) []byte { bs := make([]byte, size, size) -- cgit v1.2.3