Skip to content

Commit

Permalink
update C
Browse files Browse the repository at this point in the history
  • Loading branch information
bddicken committed Dec 9, 2024
1 parent aac1afa commit a53c8a7
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 27 deletions.
18 changes: 6 additions & 12 deletions levenshtein/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,7 @@ int levenshtein(const char *str1, const char *str2) { // A function that takes
matrix[i] = malloc((n + 1) * sizeof(int));
}

for (int i = 0; i <= m; i++) { // Matrix initialization step to generate first row and column.
matrix[i][0] = i;
}
for (int j = 0; j <= n; j++) {
matrix[0][j] = j;
}
int matrix[m+1][n+1]; // Matrix initialization step to generate first row and column.

for (int i = 1; i <= m; i++) { // Entire levenshtein matrix must be populated
for (int j = 1; j <= n; j++) { // Using standard / naive levenshtein algorithm
Expand All @@ -44,12 +39,11 @@ int levenshtein(const char *str1, const char *str2) { // A function that takes
}
}

int distance = matrix[m][n]; // The matrix must be cleaned up.
for (int i = 0; i <= m; i++) { // For a heap allocation this means some form of cleanup
free(matrix[i]); // If stack was used, should just clean up when returning
}
free(matrix);
return distance; // Return distance
// The matrix must be cleaned up.
// For a heap allocation this means some form of cleanup
// For example, in C, call(s) to free()
// If stack was used, should just clean up when returning
return matrix[m][n];
}

int main(int argc, char *argv[]) { // Program accepts any number of string inputs on the command line
Expand Down
17 changes: 2 additions & 15 deletions levenshtein/c/code.c
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,7 @@ int levenshtein_distance(const char *str1, const char *str2) {
int n = strlen(str2);

// Create a matrix to store distances
int **matrix = malloc((m + 1) * sizeof(int *));
for (int i = 0; i <= m; i++) {
matrix[i] = malloc((n + 1) * sizeof(int));
}
int matrix[m+1][n+1];

// Initialize first row and column
for (int i = 0; i <= m; i++) {
Expand All @@ -40,17 +37,7 @@ int levenshtein_distance(const char *str1, const char *str2) {
}
}

// Store the final distance
int distance = matrix[m][n];

// Free the allocated memory
// This could be faster without malloc :)
for (int i = 0; i <= m; i++) {
free(matrix[i]);
}
free(matrix);

return distance;
return matrix[m][n];
}

int main(int argc, char *argv[]) {
Expand Down

0 comments on commit a53c8a7

Please sign in to comment.