From e0419b338e3c3aa34b6ab1ee7b10cabdab0d281a Mon Sep 17 00:00:00 2001 From: Pieter Eendebak Date: Fri, 22 Apr 2022 20:16:40 +0200 Subject: [PATCH 1/2] replace multiplication with sum in initialization of row buffer --- Python/suggestions.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Python/suggestions.c b/Python/suggestions.c index d9e69fa7e0db21..38bf9e7325d001 100644 --- a/Python/suggestions.c +++ b/Python/suggestions.c @@ -78,9 +78,10 @@ levenshtein_distance(const char *a, size_t a_size, // Instead of producing the whole traditional len(a)-by-len(b) // matrix, we can update just one row in place. // Initialize the buffer row - for (size_t i = 0; i < a_size; i++) { + buffer[0] = MOVE_COST; + for (size_t i = 1; i < a_size; i++) { // cost from b[:0] to a[:i+1] - buffer[i] = (i + 1) * MOVE_COST; + buffer[i] = buffer[i-1] + MOVE_COST; } size_t result = 0; From 1c10536dae71332263bc9d8bc614c6720073079f Mon Sep 17 00:00:00 2001 From: Pieter Eendebak Date: Fri, 22 Apr 2022 22:52:52 +0200 Subject: [PATCH 2/2] avoid buffer reads --- Python/suggestions.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Python/suggestions.c b/Python/suggestions.c index 38bf9e7325d001..b84acaaed6b1fd 100644 --- a/Python/suggestions.c +++ b/Python/suggestions.c @@ -78,10 +78,11 @@ levenshtein_distance(const char *a, size_t a_size, // Instead of producing the whole traditional len(a)-by-len(b) // matrix, we can update just one row in place. // Initialize the buffer row - buffer[0] = MOVE_COST; - for (size_t i = 1; i < a_size; i++) { + size_t tmp = MOVE_COST; + for (size_t i = 0; i < a_size; i++) { // cost from b[:0] to a[:i+1] - buffer[i] = buffer[i-1] + MOVE_COST; + buffer[i] = tmp; + tmp += MOVE_COST; } size_t result = 0;