aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorCY Fung <fungcheokyin@gmail.com>2023-12-24 21:15:32 +0800
committerCY Fung <fungcheokyin@gmail.com>2023-12-24 21:15:32 +0800
commit7e1c1b471d7602a848cd71cd265b0e0a78ceacd9 (patch)
tree480fce0e5b954e0d9f3e306a1060db35158bb71e
parent4f2f08eefa31bd54d6cf3ae7258f090c0f267f3b (diff)
downloadperlweeklychallenge-club-7e1c1b471d7602a848cd71cd265b0e0a78ceacd9.tar.gz
perlweeklychallenge-club-7e1c1b471d7602a848cd71cd265b0e0a78ceacd9.tar.bz2
perlweeklychallenge-club-7e1c1b471d7602a848cd71cd265b0e0a78ceacd9.zip
Week 248
-rw-r--r--challenge-248/cheok-yin-fung/perl/ch-1.pl30
-rw-r--r--challenge-248/cheok-yin-fung/perl/ch-2.pl42
2 files changed, 72 insertions, 0 deletions
diff --git a/challenge-248/cheok-yin-fung/perl/ch-1.pl b/challenge-248/cheok-yin-fung/perl/ch-1.pl
new file mode 100644
index 0000000000..d322be06e6
--- /dev/null
+++ b/challenge-248/cheok-yin-fung/perl/ch-1.pl
@@ -0,0 +1,30 @@
+# The Weekly Challenge 248
+# Task 1 Shortest Distance
+use v5.30.0;
+use warnings;
+use List::Util qw/min/;
+
+sub sd {
+ my $str = $_[0];
+ my $chr = $_[1];
+ my @arr;
+ my $pre_k = 0;
+ my $k = index($str,$chr,$pre_k);
+ while ($k != -1 && $k < length $str) {
+ $arr[$k] = 0;
+ my $nxt_k = index($str,$chr,$k+1);
+ $nxt_k = length $str if $nxt_k == -1;
+ for my $j ($pre_k..$nxt_k-1) {
+ $arr[$j] = defined($arr[$j]) ? min($arr[$j], $k-$j): abs($k-$j);
+ }
+ $pre_k = $k;
+ $k = $nxt_k;
+ }
+ return [@arr];
+}
+
+use Test2::V0;
+is sd("loveleetcode", "e"), [3,2,1,0,1,0,0,1,2,2,1,0];
+is sd("aaab","b"), [3,2,1,0];
+is sd("baaa","b"), [0,1,2,3];
+done_testing();
diff --git a/challenge-248/cheok-yin-fung/perl/ch-2.pl b/challenge-248/cheok-yin-fung/perl/ch-2.pl
new file mode 100644
index 0000000000..d32fa9f6d1
--- /dev/null
+++ b/challenge-248/cheok-yin-fung/perl/ch-2.pl
@@ -0,0 +1,42 @@
+# The Weekly Challenge 248
+# Task 2 Submatrix Sum
+use v5.30.0;
+use warnings;
+
+sub ss {
+ my @mat = $_[0]->@*;
+ my $b;
+ for my $i (0..$#mat-1) {
+ for my $k (0..$mat[0]->$#*-1) {
+ $b->[$i][$k] = $mat[$i][$k]+$mat[$i][$k+1]
+ + $mat[$i+1][$k]+$mat[$i+1][$k+1];
+ }
+ }
+ return $b;
+}
+
+use Test2::V0;
+is(ss([
+ [1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12]
+ ]),
+ [
+ [14, 18, 22],
+ [30, 34, 38]
+ ]
+);
+
+is(ss( [
+ [1, 0, 0, 0],
+ [0, 1, 0, 0],
+ [0, 0, 1, 0],
+ [0, 0, 0, 1]
+ ]),
+ [
+ [2, 1, 0],
+ [1, 2, 1],
+ [0, 1, 2]
+ ]
+);
+done_testing();