Advertisement
Dannykcw

Untitled

Apr 27th, 2025
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.58 KB | Source Code | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. int editDist(char* word1, char* word2);
  6. int min(int a, int b);
  7. void swap(int** a, int** b);
  8.  
  9. int min(int a, int b){
  10.   return a < b ? a:b;
  11. }
  12.  
  13. void swap(int** a, int** b){
  14.   int* temp = *a;
  15.   *a = *b;
  16.   *b = temp;
  17. }
  18.  
  19. int editDist(char* word1, char* word2){
  20.  
  21.   int word1_len = strlen(word1);
  22.   int word2_len = strlen(word2);
  23.   int* oldDist = (int*)malloc((word2_len + 1) * sizeof(int));
  24.   int* curDist = (int*)malloc((word2_len + 1) * sizeof(int));
  25.  
  26.   int i,j,dist;
  27.  
  28.   //initialize distances to length of the substrings
  29.   for(i = 0; i < word2_len + 1; i++){
  30.     oldDist[i] = i;
  31.     curDist[i] = i;
  32.   }
  33.  
  34.   for(i = 1; i < word1_len + 1; i++){
  35.     curDist[0] = i;
  36.     for(j = 1; j < word2_len + 1; j++){
  37.       if(word1[i-1] == word2[j-1]){
  38.         curDist[j] = oldDist[j - 1];
  39.       }//the characters in the words are the same
  40.       else{
  41.         curDist[j] = min(min(oldDist[j], //deletion
  42.                           curDist[j-1]), //insertion
  43.                           oldDist[j-1]) + 1; //subs titution
  44.       }
  45.     }//for each character in the second word
  46.     swap(&oldDist, &curDist);
  47.   }//for each character in the first word
  48.  
  49.   dist = oldDist[word2_len];//using oldDist instead of curDist because of the last swap
  50.   free(oldDist);
  51.   free(curDist);
  52.   return dist;
  53.  
  54. }
  55.  
  56. int main(int argc, char** argv){
  57.   if(argc < 3){
  58.     printf("Usage: %s word1 word 2\n", argv[0]);
  59.     exit(1);
  60.   }
  61.   printf("The distance between %s and %s is %d.\n", argv[1], argv[2], editDist(argv[1], argv[2]));
  62.  
  63.   return 0;
  64. }
  65.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement