String-Similarity-1.04/0000755000000000000000000000000011223406043013521 5ustar rootrootString-Similarity-1.04/Similarity.xs0000644000000000000000000000200211104064452016217 0ustar rootroot#include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include "fstrcmp.h" #include "fstrcmp.c" UV * text2UV (SV *sv, STRLEN *lenp) { STRLEN len; char *s = SvPV (sv, len); UV *r = (UV *)SvPVX (sv_2mortal (NEWSV (0, (len + 1) * sizeof (UV)))); UV *p = r; if (SvUTF8 (sv)) { STRLEN clen; while (len) { *p++ = utf8n_to_uvchr (s, len, &clen, 0); if (clen < 0) croak ("illegal unicode character in string"); s += clen; len -= clen; } } else while (len--) *p++ = *(unsigned char *)s++; *lenp = p - r; return r; } MODULE = String::Similarity PACKAGE = String::Similarity double fstrcmp(s1, s2, minimum_similarity = 0) SV * s1 SV * s2 double minimum_similarity PROTOTYPE: @ CODE: { STRLEN l1, l2; UV *c1 = text2UV (s1, &l1); UV *c2 = text2UV (s2, &l2); RETVAL = fstrcmp (c1, l1, c2, l2, minimum_similarity); } OUTPUT: RETVAL String-Similarity-1.04/META.yml0000644000000000000000000000073311223406043014775 0ustar rootroot--- #YAML:1.0 name: String-Similarity version: 1.04 abstract: ~ author: [] license: unknown distribution_type: module configure_requires: ExtUtils::MakeMaker: 0 build_requires: ExtUtils::MakeMaker: 0 requires: {} no_index: directory: - t - inc generated_by: ExtUtils::MakeMaker version 6.50 meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: 1.4 String-Similarity-1.04/COPYING0000644000000000000000000004311610211640741014562 0ustar rootroot GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19yy name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. String-Similarity-1.04/Changes0000644000000000000000000000216311223406036015020 0ustar rootrootRevision history for Perl extension String::Similarity 1.04 Fri Jul 3 15:48:09 CEST 2009 - work around atrocious bugs in activestate windows, which pollutes the namespace with nonstandard symbols, equalling only the bush junta in brokenness. 1.03 Mon Jun 11 23:15:35 CEST 2007 - bump the version number, seems cpan ignored the 1.02 upload. 1.02 Mon Feb 12 16:26:08 CET 2007 - add missing use Exporter, add use DynaLoader for symmetry and because I was told some bug in bleadperl might require that. - add 'no warnings' to testsuite. If your perl is too old, remove it. 1.01 Thu Mar 3 18:00:52 CET 2005 - change of contact address. 1.0 Fri Jan 30 15:16:16 CET 2004 - Fixed correctness in the presence of non-latin1-characters, at a small speed penalty. Based on an idea by Dave Evans. - perl 5.8.x+ required. 0.02 Thu Nov 16 01:30:16 CET 2000 - added minimum_similarity limit to speed up some searches - last version to work with perls <5.8.x. 0.01 Fri Apr 7 08:03:08 CEST 2000 - original version; leftover "garbage" from the PApp module String-Similarity-1.04/t/0000755000000000000000000000000011223406043013764 5ustar rootrootString-Similarity-1.04/t/00_load.t0000644000000000000000000000201510257225051015371 0ustar rootrootBEGIN { $| = 1; print "1..10\n"; } END {print "not ok 1\n" unless $loaded;} use String::Similarity; $loaded = 1; print "ok 1\n"; print similarity("this should be the same", "this should be the same") == 1 ? "" : "not ", "ok 2\n"; my $s = similarity("this should be same the", "this should be the same"); print $s > 0.825 && $s < 0.827 ? "" : "not ", "ok 3\n"; print similarity("A", "B") == 0 ? "" : "not ", "ok 4\n"; print similarity("\x{456}", "\x{455}") == 0 ? "" : "not ", "ok 5\n"; require utf8; $a = chr(169); utf8::upgrade($b = $a); print similarity($a, $b) == 1 ? "" : "not ", "ok 6\n"; $b = "\x{0040}"; utf8::downgrade($a = $b); print similarity($a, $b) == 1 ? "" : "not ", "ok 7\n"; utf8::upgrade($a = chr(169)); use Encode qw( encode ); $b = encode "utf-8", $a; print similarity($a, $b) < 1 ? "" : "not ", "ok 8\n"; $a = []; $b = []; $s1 = similarity($a, $b); $s2 = similarity($a, "$b"); print "not " unless abs($s1-$s2) < 0.001; print "ok 9\n"; $s = similarity("", undef); print "not " unless $s == 1; print "ok 10\n"; String-Similarity-1.04/MANIFEST0000644000000000000000000000035510211640741014656 0ustar rootrootREADME Changes MANIFEST COPYING Makefile.PL Similarity.pm Similarity.xs fstrcmp.h fstrcmp (from gnu gettext) fstrcmp.c fstrcmp (from gnu gettext) t/00_load.t META.yml Module meta-data (added by MakeMaker) String-Similarity-1.04/fstrcmp.c0000644000000000000000000003751511104065210015351 0ustar rootroot/* Functions to make fuzzy comparisons between strings Copyright (C) 1988, 1989, 1992, 1993, 1995 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. Derived from GNU diff 2.7, analyze.c et al. The basic algorithm is described in: "An O(ND) Difference Algorithm and its Variations", Eugene Myers, Algorithmica Vol. 1 No. 2, 1986, pp. 251-266; see especially section 4.2, which describes the variation used below. The basic algorithm was independently discovered as described in: "Algorithms for Approximate String Matching", E. Ukkonen, Information and Control Vol. 64, 1985, pp. 100-118. Modified to work on strings rather than files by Peter Miller , October 1995 Modified to accept a "minimum similarity limit" to stop analyzing the string when the similarity drops below the given limit by Marc Lehmann . Modified to work on unicode (actually 31 bit are allowed) by Marc Lehmann . */ #include #include #include #include #include "fstrcmp.h" #define PARAMS(proto) proto /* * Data on one input string being compared. */ struct string_data { /* The string to be compared. */ const UV *data; /* The length of the string to be compared. */ int data_length; /* The number of characters inserted or deleted. */ int edit_count; }; static struct string_data string[2]; static int max_edits; /* compareseq stops when edits > max_edits */ #ifdef MINUS_H_FLAG /* This corresponds to the diff -H flag. With this heuristic, for strings with a constant small density of changes, the algorithm is linear in the strings size. This is unlikely in typical uses of fstrcmp, and so is usually compiled out. Besides, there is no interface to set it true. */ static int heuristic; #endif /* Vector, indexed by diagonal, containing 1 + the X coordinate of the point furthest along the given diagonal in the forward search of the edit matrix. */ static int *fdiag; /* Vector, indexed by diagonal, containing the X coordinate of the point furthest along the given diagonal in the backward search of the edit matrix. */ static int *bdiag; /* Edit scripts longer than this are too expensive to compute. */ static int too_expensive; /* Snakes bigger than this are considered `big'. */ #define SNAKE_LIMIT 20 struct partition { /* Midpoints of this partition. */ int xmid, ymid; /* Nonzero if low half will be analyzed minimally. */ int lo_minimal; /* Likewise for high half. */ int hi_minimal; }; /* NAME diag - find diagonal path SYNOPSIS int diag(int xoff, int xlim, int yoff, int ylim, int minimal, struct partition *part); DESCRIPTION Find the midpoint of the shortest edit script for a specified portion of the two strings. Scan from the beginnings of the strings, and simultaneously from the ends, doing a breadth-first search through the space of edit-sequence. When the two searches meet, we have found the midpoint of the shortest edit sequence. If MINIMAL is nonzero, find the minimal edit script regardless of expense. Otherwise, if the search is too expensive, use heuristics to stop the search and report a suboptimal answer. RETURNS Set PART->(XMID,YMID) to the midpoint (XMID,YMID). The diagonal number XMID - YMID equals the number of inserted characters minus the number of deleted characters (counting only characters before the midpoint). Return the approximate edit cost; this is the total number of characters inserted or deleted (counting only characters before the midpoint), unless a heuristic is used to terminate the search prematurely. Set PART->LEFT_MINIMAL to nonzero iff the minimal edit script for the left half of the partition is known; similarly for PART->RIGHT_MINIMAL. CAVEAT This function assumes that the first characters of the specified portions of the two strings do not match, and likewise that the last characters do not match. The caller must trim matching characters from the beginning and end of the portions it is going to specify. If we return the "wrong" partitions, the worst this can do is cause suboptimal diff output. It cannot cause incorrect diff output. */ static int diag PARAMS ((int, int, int, int, int, struct partition *)); static int diag (xoff, xlim, yoff, ylim, minimal, part) int xoff; int xlim; int yoff; int ylim; int minimal; struct partition *part; { int *const fd = fdiag; /* Give the compiler a chance. */ int *const bd = bdiag; /* Additional help for the compiler. */ const UV *const xv = string[0].data; /* Still more help for the compiler. */ const UV *const yv = string[1].data; /* And more and more . . . */ const int dmin = xoff - ylim; /* Minimum valid diagonal. */ const int dmax = xlim - yoff; /* Maximum valid diagonal. */ const int fmid = xoff - yoff; /* Center diagonal of top-down search. */ const int bmid = xlim - ylim; /* Center diagonal of bottom-up search. */ int fmin = fmid; int fmax = fmid; /* Limits of top-down search. */ int bmin = bmid; int bmax = bmid; /* Limits of bottom-up search. */ int c; /* Cost. */ int odd = (fmid - bmid) & 1; /* * True if southeast corner is on an odd diagonal with respect * to the northwest. */ fd[fmid] = xoff; bd[bmid] = xlim; for (c = 1;; ++c) { int d; /* Active diagonal. */ int big_snake; big_snake = 0; /* Extend the top-down search by an edit step in each diagonal. */ if (fmin > dmin) fd[--fmin - 1] = -1; else ++fmin; if (fmax < dmax) fd[++fmax + 1] = -1; else --fmax; for (d = fmax; d >= fmin; d -= 2) { int x; int y; int oldx; int tlo; int thi; tlo = fd[d - 1], thi = fd[d + 1]; if (tlo >= thi) x = tlo + 1; else x = thi; oldx = x; y = x - d; while (x < xlim && y < ylim && xv[x] == yv[y]) { ++x; ++y; } if (x - oldx > SNAKE_LIMIT) big_snake = 1; fd[d] = x; if (odd && bmin <= d && d <= bmax && bd[d] <= x) { part->xmid = x; part->ymid = y; part->lo_minimal = part->hi_minimal = 1; return 2 * c - 1; } } /* Similarly extend the bottom-up search. */ if (bmin > dmin) bd[--bmin - 1] = INT_MAX; else ++bmin; if (bmax < dmax) bd[++bmax + 1] = INT_MAX; else --bmax; for (d = bmax; d >= bmin; d -= 2) { int x; int y; int oldx; int tlo; int thi; tlo = bd[d - 1], thi = bd[d + 1]; if (tlo < thi) x = tlo; else x = thi - 1; oldx = x; y = x - d; while (x > xoff && y > yoff && xv[x - 1] == yv[y - 1]) { --x; --y; } if (oldx - x > SNAKE_LIMIT) big_snake = 1; bd[d] = x; if (!odd && fmin <= d && d <= fmax && x <= fd[d]) { part->xmid = x; part->ymid = y; part->lo_minimal = part->hi_minimal = 1; return 2 * c; } } if (minimal) continue; #ifdef MINUS_H_FLAG /* Heuristic: check occasionally for a diagonal that has made lots of progress compared with the edit distance. If we have any such, find the one that has made the most progress and return it as if it had succeeded. With this heuristic, for strings with a constant small density of changes, the algorithm is linear in the strings size. */ if (c > 200 && big_snake && heuristic) { int best; best = 0; for (d = fmax; d >= fmin; d -= 2) { int dd; int x; int y; int v; dd = d - fmid; x = fd[d]; y = x - d; v = (x - xoff) * 2 - dd; if (v > 12 * (c + (dd < 0 ? -dd : dd))) { if ( v > best && xoff + SNAKE_LIMIT <= x && x < xlim && yoff + SNAKE_LIMIT <= y && y < ylim ) { /* We have a good enough best diagonal; now insist that it end with a significant snake. */ int k; for (k = 1; xv[x - k] == yv[y - k]; k++) { if (k == SNAKE_LIMIT) { best = v; part->xmid = x; part->ymid = y; break; } } } } } if (best > 0) { part->lo_minimal = 1; part->hi_minimal = 0; return 2 * c - 1; } best = 0; for (d = bmax; d >= bmin; d -= 2) { int dd; int x; int y; int v; dd = d - bmid; x = bd[d]; y = x - d; v = (xlim - x) * 2 + dd; if (v > 12 * (c + (dd < 0 ? -dd : dd))) { if (v > best && xoff < x && x <= xlim - SNAKE_LIMIT && yoff < y && y <= ylim - SNAKE_LIMIT) { /* We have a good enough best diagonal; now insist that it end with a significant snake. */ int k; for (k = 0; xv[x + k] == yv[y + k]; k++) { if (k == SNAKE_LIMIT - 1) { best = v; part->xmid = x; part->ymid = y; break; } } } } } if (best > 0) { part->lo_minimal = 0; part->hi_minimal = 1; return 2 * c - 1; } } #endif /* MINUS_H_FLAG */ /* Heuristic: if we've gone well beyond the call of duty, give up and report halfway between our best results so far. */ if (c >= too_expensive) { int fxybest; int fxbest; int bxybest; int bxbest; /* Pacify `gcc -Wall'. */ fxbest = 0; bxbest = 0; /* Find forward diagonal that maximizes X + Y. */ fxybest = -1; for (d = fmax; d >= fmin; d -= 2) { int x; int y; x = fd[d] < xlim ? fd[d] : xlim; y = x - d; if (ylim < y) { x = ylim + d; y = ylim; } if (fxybest < x + y) { fxybest = x + y; fxbest = x; } } /* Find backward diagonal that minimizes X + Y. */ bxybest = INT_MAX; for (d = bmax; d >= bmin; d -= 2) { int x; int y; x = xoff > bd[d] ? xoff : bd[d]; y = x - d; if (y < yoff) { x = yoff + d; y = yoff; } if (x + y < bxybest) { bxybest = x + y; bxbest = x; } } /* Use the better of the two diagonals. */ if ((xlim + ylim) - bxybest < fxybest - (xoff + yoff)) { part->xmid = fxbest; part->ymid = fxybest - fxbest; part->lo_minimal = 1; part->hi_minimal = 0; } else { part->xmid = bxbest; part->ymid = bxybest - bxbest; part->lo_minimal = 0; part->hi_minimal = 1; } return 2 * c - 1; } } } /* NAME compareseq - find edit sequence SYNOPSIS void compareseq(int xoff, int xlim, int yoff, int ylim, int minimal); DESCRIPTION Compare in detail contiguous subsequences of the two strings which are known, as a whole, to match each other. The subsequence of string 0 is [XOFF, XLIM) and likewise for string 1. Note that XLIM, YLIM are exclusive bounds. All character numbers are origin-0. If MINIMAL is nonzero, find a minimal difference no matter how expensive it is. */ static void compareseq PARAMS ((int, int, int, int, int)); static void compareseq (xoff, xlim, yoff, ylim, minimal) int xoff; int xlim; int yoff; int ylim; int minimal; { const UV *const xv = string[0].data; /* Help the compiler. */ const UV *const yv = string[1].data; if (string[1].edit_count + string[0].edit_count > max_edits) return; /* Slide down the bottom initial diagonal. */ while (xoff < xlim && yoff < ylim && xv[xoff] == yv[yoff]) { ++xoff; ++yoff; } /* Slide up the top initial diagonal. */ while (xlim > xoff && ylim > yoff && xv[xlim - 1] == yv[ylim - 1]) { --xlim; --ylim; } /* Handle simple cases. */ if (xoff == xlim) { while (yoff < ylim) { ++string[1].edit_count; ++yoff; } } else if (yoff == ylim) { while (xoff < xlim) { ++string[0].edit_count; ++xoff; } } else { int c; struct partition part; /* Find a point of correspondence in the middle of the strings. */ c = diag (xoff, xlim, yoff, ylim, minimal, &part); if (c == 1) { #if 0 /* This should be impossible, because it implies that one of the two subsequences is empty, and that case was handled above without calling `diag'. Let's verify that this is true. */ abort (); #else /* The two subsequences differ by a single insert or delete; record it and we are done. */ if (part.xmid - part.ymid < xoff - yoff) ++string[1].edit_count; else ++string[0].edit_count; #endif } else { /* Use the partitions to split this problem into subproblems. */ compareseq (xoff, part.xmid, yoff, part.ymid, part.lo_minimal); compareseq (part.xmid, xlim, part.ymid, ylim, part.hi_minimal); } } } /* NAME fstrcmp - fuzzy string compare SYNOPSIS double fstrcmp(const ChaR *s1, int l1, const UV *s2, int l2, double); DESCRIPTION The fstrcmp function may be used to compare two string for similarity. It is very useful in reducing "cascade" or "secondary" errors in compilers or other situations where symbol tables occur. RETURNS double; 0 if the strings are entirly dissimilar, 1 if the strings are identical, and a number in between if they are similar. */ double fstrcmp (const UV *string1, int length1, const UV *string2, int length2, double minimum) { int i; size_t fdiag_len; static int *fdiag_buf; static size_t fdiag_max; /* set the info for each string. */ string[0].data = string1; string[0].data_length = length1; string[1].data = string2; string[1].data_length = length2; /* short-circuit obvious comparisons */ if (string[0].data_length == 0 && string[1].data_length == 0) return 1.0; if (string[0].data_length == 0 || string[1].data_length == 0) return 0.0; /* Set TOO_EXPENSIVE to be approximate square root of input size, bounded below by 256. */ too_expensive = 1; for (i = string[0].data_length + string[1].data_length; i != 0; i >>= 2) too_expensive <<= 1; if (too_expensive < 256) too_expensive = 256; /* Because fstrcmp is typically called multiple times, while scanning symbol tables, etc, attempt to minimize the number of memory allocations performed. Thus, we use a static buffer for the diagonal vectors, and never free them. */ fdiag_len = string[0].data_length + string[1].data_length + 3; if (fdiag_len > fdiag_max) { fdiag_max = fdiag_len; fdiag_buf = realloc (fdiag_buf, fdiag_max * (2 * sizeof (int))); } fdiag = fdiag_buf + string[1].data_length + 1; bdiag = fdiag + fdiag_len; max_edits = 1 + (string[0].data_length + string[1].data_length) * (1. - minimum); /* Now do the main comparison algorithm */ string[0].edit_count = 0; string[1].edit_count = 0; compareseq (0, string[0].data_length, 0, string[1].data_length, 0); /* The result is ((number of chars in common) / (average length of the strings)). This is admittedly biased towards finding that the strings are similar, however it does produce meaningful results. */ return ((double) (string[0].data_length + string[1].data_length - string[1].edit_count - string[0].edit_count) / (string[0].data_length + string[1].data_length)); } String-Similarity-1.04/README0000644000000000000000000000355311223406043014407 0ustar rootrootNAME String::Similarity - calculate the similarity of two strings SYNOPSIS use String::Similarity; $similarity = similarity $string1, $string2; $similarity = similarity $string1, $string2, $limit; DESCRIPTION $factor = similarity $string1, $string2, [$limit] The "similarity"-function calculates the similarity index of its two arguments. A value of 0 means that the strings are entirely different. A value of 1 means that the strings are identical. Everything else lies between 0 and 1 and describes the amount of similarity between the strings. It roughly works by looking at the smallest number of edits to change one string into the other. You can add an optional argument $limit (default 0) that gives the minimum similarity the two strings must satisfy. "similarity" stops analyzing the string as soon as the result drops below the given limit, in which case the result will be invalid but lower than the given $limit. You can use this to speed up the common case of searching for the most similar string from a set by specifing the maximum similarity found so far. SEE ALSO The basic algorithm is described in: "An O(ND) Difference Algorithm and its Variations", Eugene Myers, Algorithmica Vol. 1 No. 2, 1986, pp. 251-266; see especially section 4.2, which describes the variation used below. The basic algorithm was independently discovered as described in: "Algorithms for Approximate String Matching", E. Ukkonen, Information and Control Vol. 64, 1985, pp. 100-118. AUTHOR Marc Lehmann http://home.schmorp.de/ (the underlying fstrcmp function was taken from gnu diffutils and modified by Peter Miller and Marc Lehmann ). String-Similarity-1.04/Makefile.PL0000644000000000000000000000052010211640741015471 0ustar rootrootrequire 5.008; use ExtUtils::MakeMaker; WriteMakefile( dist => { PREOP => 'pod2text Similarity.pm | tee README >$(DISTVNAME)/README; chmod -R u=rwX,go=rX . ;', COMPRESS => 'gzip -9v', SUFFIX => '.gz', }, NAME => "String::Similarity", VERSION_FROM => "Similarity.pm", ); String-Similarity-1.04/Similarity.pm0000644000000000000000000000410211104064640016203 0ustar rootroot=head1 NAME String::Similarity - calculate the similarity of two strings =head1 SYNOPSIS use String::Similarity; $similarity = similarity $string1, $string2; $similarity = similarity $string1, $string2, $limit; =head1 DESCRIPTION =over 4 =cut package String::Similarity; use Exporter; use DynaLoader; $VERSION = '1.04'; @ISA = qw/Exporter DynaLoader/; @EXPORT = qw(similarity); @EXPORT_OK = qw(fstrcmp); bootstrap String::Similarity $VERSION; =item $factor = similarity $string1, $string2, [$limit] The C-function calculates the similarity index of its two arguments. A value of C<0> means that the strings are entirely different. A value of C<1> means that the strings are identical. Everything else lies between 0 and 1 and describes the amount of similarity between the strings. It roughly works by looking at the smallest number of edits to change one string into the other. You can add an optional argument C<$limit> (default 0) that gives the minimum similarity the two strings must satisfy. C stops analyzing the string as soon as the result drops below the given limit, in which case the result will be invalid but lower than the given C<$limit>. You can use this to speed up the common case of searching for the most similar string from a set by specifing the maximum similarity found so far. =cut # out of historical reasons, I prefer "fstrcmp" as the original name. *similarity = *fstrcmp; 1; =back =head1 SEE ALSO The basic algorithm is described in: "An O(ND) Difference Algorithm and its Variations", Eugene Myers, Algorithmica Vol. 1 No. 2, 1986, pp. 251-266; see especially section 4.2, which describes the variation used below. The basic algorithm was independently discovered as described in: "Algorithms for Approximate String Matching", E. Ukkonen, Information and Control Vol. 64, 1985, pp. 100-118. =head1 AUTHOR Marc Lehmann http://home.schmorp.de/ (the underlying fstrcmp function was taken from gnu diffutils and modified by Peter Miller and Marc Lehmann ). String-Similarity-1.04/fstrcmp.h0000644000000000000000000000170211104065206015350 0ustar rootroot/* GNU gettext - internationalization aids Copyright (C) 1995 Free Software Foundation, Inc. This file was written by Peter Miller This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef _FSTRCMP_H #define _FSTRCMP_H double fstrcmp (const UV *__s1, int __l1, const UV *__s2, int __l2, double __minimum); #endif