Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Hamming distance #15

Merged
merged 2 commits into from
Nov 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions .spec/string/distance/hamming_spec.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
describe("Hamming distance", function()
local hamming_distance = require("string.distance.hamming")

local function check_basic(a, b, expected)
assert.equal(expected, hamming_distance(a, b))
assert.equal(0, hamming_distance(a, a))
end

local function check_with_reversed_inputs(a, b, expected)
assert.equal(expected, hamming_distance(a:reverse(), b:reverse()))
assert.equal(0, hamming_distance(a:reverse(), a:reverse()))
end

local function check_all(a, b, expected)
check_basic(a, b, expected)
check_with_reversed_inputs(a, b, expected)
end

local function test(a, b, expected)
check_all(a, b, expected)
check_all(b, a, expected)
end

it("should handle general cases", function()
test("", "", 0)
test("a", "a", 0)
test("a", "A", 1)
test("cąx", "cąy", 1)
test("mama", "tata", 2)
test("xxx", "Xxx", 1)
test("1234", "2345", 4)
end)

it("should throw error for inputs of different length", function()
assert.has_error(function()
hamming_distance("z", "")
end)
end)
end)
15 changes: 15 additions & 0 deletions src/string/distance/hamming.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
-- Computes the Hamming "edit" distance for two strings of the same length:
-- The number of indices at which the corresponding bytes are different.
return function(
a, -- some string
b -- other string
)
assert(#a == #b, "lengths don't match")
local dist = 0
for i = 1, #a do
if a:byte(i) ~= b:byte(i) then
dist = dist + 1
end
end
return dist
end
Loading