From aac88a90a9c288b85bd4dad14bc788d37bb934bb Mon Sep 17 00:00:00 2001 From: "Gustavo L. de M. Chaves" Date: Fri, 22 Jan 2021 22:26:17 -0300 Subject: Add Gustavo Chaves's solutions to challenge 096 --- challenge-096/gustavo-chaves/perl/ch-1.pl | 13 +++++++++++ challenge-096/gustavo-chaves/perl/ch-2.pl | 36 +++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100755 challenge-096/gustavo-chaves/perl/ch-1.pl create mode 100755 challenge-096/gustavo-chaves/perl/ch-2.pl diff --git a/challenge-096/gustavo-chaves/perl/ch-1.pl b/challenge-096/gustavo-chaves/perl/ch-1.pl new file mode 100755 index 0000000000..36ee8b727a --- /dev/null +++ b/challenge-096/gustavo-chaves/perl/ch-1.pl @@ -0,0 +1,13 @@ +#!/usr/bin/env perl + +# https://perlweeklychallenge.org/blog/perl-weekly-challenge-096/ +# TASK #1 › Reverse Words + +use 5.030; +use warnings; + +my $S = shift; + +local $, = ' '; + +say reverse grep {length} split ' ', $S; diff --git a/challenge-096/gustavo-chaves/perl/ch-2.pl b/challenge-096/gustavo-chaves/perl/ch-2.pl new file mode 100755 index 0000000000..25a0701ced --- /dev/null +++ b/challenge-096/gustavo-chaves/perl/ch-2.pl @@ -0,0 +1,36 @@ +#!/usr/bin/env perl + +# https://perlweeklychallenge.org/blog/perl-weekly-challenge-096/ +# TASK #2 › Edit Distance + +use 5.030; +use warnings; + +my $S1 = shift; +my $S2 = shift; + +my @S1 = split '', $S1; +my @S2 = split '', $S2; + +sub distance { + my ($i, $j) = @_; + + if ($i < 0 && $j < 0) { + return; + } elsif ($j < 0) { + return map {"delete '$S1[$_]'"} 0 .. $i; + } elsif ($i < 0) { + return map {"delete '$S2[$_]'"} 0 .. $j; + } elsif ($S1[$i] eq $S2[$j]) { + return distance($i-1, $j-1); + } else { + my @del = (distance($i-1, $j), "delete '$S1[$i]' from $i"); + my @ins = (distance($i, $j-1), "insert '$S2[$j]' at $j"); + my @sub = (distance($i-1, $j-1), "replace '$S1[$i]' at $i with '$S2[$j]'"); + return @{(sort {scalar(@$a) <=> scalar(@$b)} \@del, \@ins, \@sub)[0]}; + } +} + +my @ops = distance($#S1, $#S2); + +say "Operation $_: $ops[$_-1]" for 1 .. @ops; -- cgit