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

perf: reduce string comparisons in Levenshtein distance calculation #266

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
27 changes: 10 additions & 17 deletions levenshtein/zig/code.zig
Original file line number Diff line number Diff line change
Expand Up @@ -12,39 +12,34 @@ fn levenshteinDistance(s1: []const u8, s2: []const u8) usize {
// Make s1 the shorter string for space optimization
const str1 = if (s1.len > s2.len) s2 else s1;
const str2 = if (s1.len > s2.len) s1 else s2;

const m = str1.len;
const n = str2.len;

// Use two arrays instead of full matrix for space optimization
var prev_row: [256]usize = undefined;
var curr_row: [256]usize = undefined;
var prev_row: [1024]usize = undefined;
var curr_row: [1024]usize = undefined;

// Initialize first row
for (0..m + 1) |i| {
prev_row[i] = i;
}

// Main computation loop
var j: usize = 1;
while (j <= n) : (j += 1) {
curr_row[0] = j;

var i: usize = 1;
while (i <= m) : (i += 1) {

const cost: usize = if (str1[i - 1] == str2[j - 1]) 0 else 1;

// Calculate minimum of three operations
curr_row[i] = @min(
@min(
prev_row[i] + 1, // deletion
curr_row[i - 1] + 1, // insertion
curr_row[i - 1] + 1 // insertion
),
prev_row[i - 1] + cost // substitution
);
}

// Swap rows
// Swap rows
@memcpy(prev_row[0..m + 1], curr_row[0..m + 1]);
}

Expand All @@ -71,15 +66,13 @@ pub fn main() !void {
// Compare all pairs of strings
var i: usize = 1;
while (i < args.len) : (i += 1) {
var j: usize = 1;
var j: usize = i + 1; // Start from i+1 to avoid redundant comparisons
while (j < args.len) : (j += 1) {
if (i != j) {
const distance = levenshteinDistance(args[i], args[j]);
if (min_distance == -1 or distance < @as(usize, @intCast(min_distance))) {
min_distance = @as(isize, @intCast(distance));
}
times += 1;
const distance = levenshteinDistance(args[i], args[j]);
if (min_distance == -1 or distance < @as(usize, @intCast(min_distance))) {
min_distance = @as(isize, @intCast(distance));
}
times += 1;
}
}

Expand Down
Loading