hammingdistance

function hammingdistance( a, b ) --> distance, err

Description

Determines the Hamming distance between two strings of equal length. The Hamming distance is the number of positions at which the corresponding byte values are different.

Parameters

a

The first string.

b

The second string.

Return Values

distance

The number of positions at which the corresponding values in the strings are different or nil if an error occurs.

err

nil or a message if the the strings have not the same length.

Code

--ZFUNC-hammingdistance-v1
local function hammingdistance( a, b ) --> distance, err
   if #a ~= #b then return nil, "strings must be of the same length" end

   local distance = 0
   for i = 1, #a do
      if string.byte( a, i ) ~= string.byte( b, i ) then
         distance = distance+1
      end
   end

   return distance
end

return hammingdistance

Examples

local t = require( "taptest" )
local hammingdistance = require( "hammingdistance" )

-- https://en.wikipedia.org/wiki/Hamming_distance#Examples
t( hammingdistance( "karolin", "kathrin" ), 3 )
t( hammingdistance( "karolin", "kerstin" ), 3 )
t( hammingdistance( "1011101", "1001001" ), 2 )
t( hammingdistance( "2173896", "2233796" ), 3 )

t()