Hello kris1511,
I tried several times your sample of code and the link that you provided us until I understand what you where trying to achieve. This is not what it is suppose to happen, this is a free forum that people are trying to assist each other for free. You need to work with your code make sure you provided us all the information that we need to replicate your problem so we can assist you as fast as possible and also to see that you have tried everything possible withing your knowledge before asking a question here. Of course this applies to all of us, not just you.
Having said that, the solution to your problem is provided bellow:
#!/usr/bin/perl use strict; use warnings; use feature 'say'; use List::Util qw( min ); sub editDistance{ my ($str1, $str2, $m, $n) = @_; return $n if $m == 0; return $m if $n == 0; return editDistance($str1, $str2, $m-1, $n-1) if substr($str1, $m, 1) eq substr($str2, $n, 1); return 1 + min ( editDistance($str1, $str2, $m, $n-1), #insert editDistance($str1, $str2, $m-1, $n), #remove editDistance($str1, $str2, $m-1, $n-1) ); #replace } my $str1 = "sunday"; my $str2 = "saturday"; say editDistance($str1, $str2, length($str1), length($str2)); __END__ $ perl test.pl 3
The reason that you where not getting the expected result is because you need to understand what happens with substr. Read again and again and see my update.
Update: From the nice implementation of fellow monk roboticus, just for testing purposes:
#!/usr/bin/perl use strict; use warnings; use feature 'say'; use List::Util qw( min ); sub editDistance{ my ($str1, $str2, $m, $n) = @_; return $n if $m == 0; return $m if $n == 0; return editDistance($str1, $str2, $m-1, $n-1) if substr($str1, $m, 1) eq substr($str2, $n, 1); return 1 + min ( editDistance($str1, $str2, $m, $n-1), #insert editDistance($str1, $str2, $m-1, $n), #remove editDistance($str1, $str2, $m-1, $n-1) ); #replace } my @pairs = ( [ "Sundayyy", "Saturday" ], [ "sunday", "saturday" ], ); for my $ar (@pairs) { my ($str1, $str2) = @$ar; say editDistance($str1, $str2, length($str1), length($str2)) . " < +$str1:$str2>"; } __END__ $ perl test.pl 5 <Sundayyy:Saturday> 3 <sunday:saturday>
Hope this helps, BR.
In reply to Re: Edit Distance Implementation in Perl
by thanos1983
in thread Edit Distance Implementation in Perl
by kris1511
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |