-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy patheditdistance.c
117 lines (91 loc) · 2.85 KB
/
editdistance.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
/* editdistance.c
A generic implementation of string comparison via dynamic programming
by:Steven Skiena
begun: March 26, 2002
*/
/*
Copyright 2003 by Steven S. Skiena; all rights reserved.
Permission is granted for use in non-commerical applications
provided this copyright notice remains intact and unchanged.
This program appears in my book:
"Programming Challenges: The Programming Contest Training Manual"
by Steven Skiena and Miguel Revilla, Springer-Verlag, New York 2003.
See our website www.programming-challenges.com for additional information.
This book can be ordered from Amazon.com at
http://www.amazon.com/exec/obidos/ASIN/0387001638/thealgorithmrepo/
*/
#include <stdio.h>
#include <string.h>
#include "editdistance.h"
/**********************************************************************/
/* [[[ editdistance_str_compare_cut */
int string_compare(char *s, char *t, cell m[MAXLEN+1][MAXLEN+1]) {
int i, j, k; /* counters */
int opt[3]; /* cost of the three options */
for (i = 0; i <= MAXLEN; i++) {
row_init(i, m);
column_init(i, m);
}
for (i = 1; i < strlen(s); i++) {
for (j = 1; j < strlen(t); j++) {
opt[MATCH] = m[i-1][j-1].cost + match(s[i], t[j]);
opt[INSERT] = m[i][j-1].cost + indel(t[j]);
opt[DELETE] = m[i-1][j].cost + indel(s[i]);
m[i][j].cost = opt[MATCH];
m[i][j].parent = MATCH;
for (k = INSERT; k <= DELETE; k++) {
if (opt[k] < m[i][j].cost) {
m[i][j].cost = opt[k];
m[i][j].parent = k;
}
}
}
}
goal_cell(s, t, &i, &j);
return(m[i][j].cost);
}
/* ]]] */
/* [[[ reconstruct_path_ed_cut */
void reconstruct_path(char *s, char *t, int i, int j, cell m[MAXLEN+1][MAXLEN+1]) {
if (m[i][j].parent == -1) {
return;
}
if (m[i][j].parent == MATCH) {
reconstruct_path(s, t, i-1, j-1, m);
match_out(s, t, i, j);
return;
}
if (m[i][j].parent == INSERT) {
reconstruct_path(s, t, i, j-1, m);
insert_out(t, j);
return;
}
if (m[i][j].parent == DELETE) {
reconstruct_path(s, t, i-1, j, m);
delete_out(s, i);
return;
}
}
/* ]]] */
void print_matrix(char *s, char *t, bool costQ, cell m[MAXLEN+1][MAXLEN+1]) {
int i, j; /* counters */
int x,y; /* string lengths */
x = strlen(s);
y = strlen(t);
printf(" ");
for (i = 0; i < y; i++) {
printf(" %c", t[i]);
}
printf("\n");
for (i = 0; i < x; i++) {
printf("%c: ", s[i]);
for (j = 0; j < y; j++) {
if (costQ == TRUE) {
printf(" %2d", m[i][j].cost);
} else {
printf(" %2d", m[i][j].parent);
}
}
printf("\n");
}
}