aboutsummaryrefslogtreecommitdiff
path: root/challenge-248/packy-anderson/perl
diff options
context:
space:
mode:
Diffstat (limited to 'challenge-248/packy-anderson/perl')
-rwxr-xr-xchallenge-248/packy-anderson/perl/ch-1.pl32
-rwxr-xr-xchallenge-248/packy-anderson/perl/ch-2.pl48
2 files changed, 80 insertions, 0 deletions
diff --git a/challenge-248/packy-anderson/perl/ch-1.pl b/challenge-248/packy-anderson/perl/ch-1.pl
new file mode 100755
index 0000000000..44ac4d4e6d
--- /dev/null
+++ b/challenge-248/packy-anderson/perl/ch-1.pl
@@ -0,0 +1,32 @@
+#!/usr/bin/env perl
+use v5.38;
+
+use List::Util qw( min );
+
+sub shortestDistance($str, $char) {
+ # split the string into an array of characters
+ my @strchar = split(//, $str);
+ # find the positions of the target $char
+ my @pos = grep { $strchar[$_] eq $char } 0 .. $#strchar;
+
+ my @output;
+ foreach my $i ( 0 .. $#strchar ) {
+ # find the distances
+ my @distance = map { abs($i - $_) } @pos;
+ # find the minimum distance
+ push @output, min(@distance);
+ }
+ return @output;
+}
+
+sub solution($str, $char) {
+ say qq{Input: \$str = "$str", \$char = "$char"};
+ my @output = shortestDistance($str, $char);
+ say 'Output: (' . join(',', @output) . ')';
+}
+
+say "Example 1:";
+solution("loveleetcode", "e");
+
+say "\nExample 2:";
+solution("aaab", "b"); \ No newline at end of file
diff --git a/challenge-248/packy-anderson/perl/ch-2.pl b/challenge-248/packy-anderson/perl/ch-2.pl
new file mode 100755
index 0000000000..c7af82634e
--- /dev/null
+++ b/challenge-248/packy-anderson/perl/ch-2.pl
@@ -0,0 +1,48 @@
+#!/usr/bin/env perl
+use v5.38;
+
+sub submatrixSum(@a) {
+ my $M = $#a; # rows
+ my $N = $#{$a[0]}; # columns
+ # we are ASSUMING the matrix is consistent with
+ # each row having the same number of columns
+ my @b;
+ foreach my $i ( 0 .. $M - 1 ) {
+ push @b, [];
+ foreach my $k ( 0 .. $N - 1 ) {
+ $b[$i]->[$k] = $a[$i]->[$k] + $a[$i]->[$k+1]
+ + $a[$i+1]->[$k] + $a[$i+1]->[$k+1];
+ }
+ }
+ return @b;
+}
+
+sub formatMatrix($matrix, $indent) {
+ my @output;
+ foreach my $row ( @$matrix ) {
+ my $output_row = q{ } x $indent . " [";
+ $output_row .= join(', ', @$row) . "]";
+ push @output, $output_row;
+ }
+ return "[\n"
+ . join(",\n", @output)
+ . "\n"
+ . q{ } x $indent . "]";
+}
+
+sub solution(@a) {
+ say 'Input: $a = ' . formatMatrix(\@a, 13);
+ my @b = submatrixSum(@a);
+ say 'Output: $b = ' . formatMatrix(\@b, 13);
+}
+
+say "Example 1:";
+solution([1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12]);
+
+say "\nExample 2:";
+solution([1, 0, 0, 0],
+ [0, 1, 0, 0],
+ [0, 0, 1, 0],
+ [0, 0, 0, 1]);