-
Notifications
You must be signed in to change notification settings - Fork 84
/
lev_dist.pl
executable file
·55 lines (46 loc) · 1.12 KB
/
lev_dist.pl
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
#!/usr/bin/perl
#
# Copyright (c) 2020 Ran Panfeng. All rights reserved.
# Author: satanson
# Email: ranpanf@gmail.com
# Github repository: https://github.com/satanson/cpp_etudes.git
#
use strict;
use warnings;
use List::Util qw/min/;
use Data::Dumper;
sub lev_dist($$){
my ($a, $b)=@_;
my ($a_len, $b_len)=(0, 0);
$a_len=length($a) if defined($a);
$b_len=length($b) if defined($b);
return $b_len if $a_len == 0;
return $a_len if $b_len == 0;
my @a = split //, lc $a;
my @b = split //, lc $b;
my ($ii, $jj) = ($a_len+1, $b_len+1);
my @d = map{[(0) x $jj]} 1 .. $ii;
for (my $i=0; $i < $ii; ++$i){
$d[$i][0] = $i;
}
for (my $j=0; $j < $jj; ++$j){
$d[0][$j] = $j;
}
for (my $i=1; $i < $ii; ++$i){
for (my $j=1; $j < $jj; ++$j){
my ($ci, $cj) = ($a[$i-1], $b[$j-1]);
if ($ci eq $cj) {
$d[$i][$j] = $d[$i-1][$j-1];
} else {
$d[$i][$j] = 1 + min($d[$i-1][$j], $d[$i][$j-1], $d[$i-1][$j-1]);
}
}
}
return $d[-1][-1];
}
my $a = "load_id";
my @b = qw/reader undef/;
for my $b (@b) {
my $dist = lev_dist($a,$b);
print "lev_dist($a, $b)=$dist\n";
}