Skip to content

Instantly share code, notes, and snippets.

@Kuxe
Last active February 10, 2018 12:50
Show Gist options
  • Save Kuxe/c9ae77b83f0110f95dbc61e6df795215 to your computer and use it in GitHub Desktop.
Save Kuxe/c9ae77b83f0110f95dbc61e6df795215 to your computer and use it in GitHub Desktop.
Computes levenshtein distance between two char pointers
#include <algorithm> //std::min, std::max
#include <cctype> //tolower
#include <array> //std::array
//Computes levenshtein-distance between two strings recursivly using dynamic programming
template<size_t MAX_STR_LEN>
constexpr static size_t levenshtein(const char* a, const char* b, const size_t len_a, const size_t len_b, std::array<std::array<size_t, MAX_STR_LEN>, MAX_STR_LEN>&& memo = {{0}}) {
return memo[len_a][len_b] != 0 ? memo[len_a][len_b] :
len_a == 0 ? memo[len_a][len_b] = len_b :
len_b == 0 ? memo[len_a][len_b] = len_a :
memo[len_a][len_b] = std::min({
levenshtein<MAX_STR_LEN>(a, b, len_a-1, len_b, std::move(memo)) + 1,
levenshtein<MAX_STR_LEN>(a, b, len_a, len_b-1, std::move(memo)) + 1,
levenshtein<MAX_STR_LEN>(a, b, len_a-1, len_b-1, std::move(memo)) + (a[len_a-1] == tolower(b[len_b-1]) ? 0 : 1)});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment