aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--challenge-271/cheok-yin-fung/perl/ch-1.pl24
-rw-r--r--challenge-271/cheok-yin-fung/perl/ch-2.pl21
2 files changed, 45 insertions, 0 deletions
diff --git a/challenge-271/cheok-yin-fung/perl/ch-1.pl b/challenge-271/cheok-yin-fung/perl/ch-1.pl
new file mode 100644
index 0000000000..70241dfa00
--- /dev/null
+++ b/challenge-271/cheok-yin-fung/perl/ch-1.pl
@@ -0,0 +1,24 @@
+# The Weekly Challenge 271
+# Task 1 Maximum Ones
+
+use v5.30.0;
+use warnings;
+
+sub mo {
+ my $mat = $_[0];
+ my $max_i;
+ my $max_one = 0;
+ for my $i (0..$mat->$#*) {
+ my $ones = grep {$_ == 1} $mat->[$i]->@*;
+ if ($ones > $max_one) {
+ $max_one = $ones;
+ $max_i = $i;
+ }
+ }
+ return $max_i+1;
+}
+
+use Test::More tests=>3;
+ok mo([[0,1],[1,0]])==1;
+ok mo([[0,0,0],[1,0,1]])==2;
+ok mo([[0,0],[1,1],[0,0]])==2;
diff --git a/challenge-271/cheok-yin-fung/perl/ch-2.pl b/challenge-271/cheok-yin-fung/perl/ch-2.pl
new file mode 100644
index 0000000000..94e581ff27
--- /dev/null
+++ b/challenge-271/cheok-yin-fung/perl/ch-2.pl
@@ -0,0 +1,21 @@
+# The Weekly Challenge 271
+# Task 2 Sort by 1 Bits
+
+use v5.30.0;
+use warnings;
+
+sub sbob {
+ my @arr = $_[0]->@*;
+ @arr = sort {num_of_one_bits($a)<=>num_of_one_bits($b) || $a<=>$b} @arr;
+ return [@arr];
+}
+
+sub num_of_one_bits {
+ my $num = $_[0];
+ my $str = unpack("B32", pack("N", $num));
+ my $ones = grep {$_==1} split "", $str;
+ return $ones;
+}
+
+say join ", ", sbob([0, 1, 2, 3, 4, 5, 6, 7, 8])->@*;
+say join ", ", sbob([1024, 512, 256, 128, 64])->@*;