aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMohammad Sajid Anwar <Mohammad.Anwar@yahoo.com>2024-04-01 00:48:47 +0100
committerGitHub <noreply@github.com>2024-04-01 00:48:47 +0100
commit40e6fa6bcc9a3abe07a6b8cf89cad2e5741b221b (patch)
tree1d62893ad5476c06478fc81b22b18e6bd19777cc
parentd1572ae61f757095dc1aa90f52e85cc0404d69de (diff)
parent30f1e1afeec3be0920e7656b36c286d0416ef69a (diff)
downloadperlweeklychallenge-club-40e6fa6bcc9a3abe07a6b8cf89cad2e5741b221b.tar.gz
perlweeklychallenge-club-40e6fa6bcc9a3abe07a6b8cf89cad2e5741b221b.tar.bz2
perlweeklychallenge-club-40e6fa6bcc9a3abe07a6b8cf89cad2e5741b221b.zip
Merge pull request #9842 from Util/c262
Add TWC 262 solutions by Bruce Gray, in Raku only.
-rw-r--r--challenge-262/bruce-gray/raku/ch-1.raku19
-rw-r--r--challenge-262/bruce-gray/raku/ch-2.raku29
2 files changed, 48 insertions, 0 deletions
diff --git a/challenge-262/bruce-gray/raku/ch-1.raku b/challenge-262/bruce-gray/raku/ch-1.raku
new file mode 100644
index 0000000000..e8dfa9543a
--- /dev/null
+++ b/challenge-262/bruce-gray/raku/ch-1.raku
@@ -0,0 +1,19 @@
+sub task1 ( @ns --> UInt ) {
+ my ( $negatives, $zeros, $positives ) = @ns».sign.Bag{-1, 0, 1};
+
+ if $zeros {
+ warn "One or more `0` was found in the input, and the task was not clear on how they were to be treated.";
+ }
+
+ return $negatives max $positives;
+}
+
+
+use Test; plan +constant @tests =
+ ( 4, ( -3, 1, 2, -1, 3, -2, 4 ) ),
+ ( 3, ( -1, -2, -3, 1 ) ),
+ ( 2, ( 1, 2 ) ),
+;
+for @tests -> ( $expected, @in ) {
+ is task1( @in ), $expected;
+}
diff --git a/challenge-262/bruce-gray/raku/ch-2.raku b/challenge-262/bruce-gray/raku/ch-2.raku
new file mode 100644
index 0000000000..64cb475af2
--- /dev/null
+++ b/challenge-262/bruce-gray/raku/ch-2.raku
@@ -0,0 +1,29 @@
+sub task2 ( UInt $k, @ns --> UInt ) {
+ # Concise, but always O(N²) :
+ # return +grep { ([*] .list) %% $k and ([==] @ns[.list]) }, combinations(+@ns, 2);
+
+ sub wanted ( ($i, $j) --> Bool ) { ($i × $j) %% $k }
+
+ sub combin_count (@indexes) { @indexes.combinations(2).grep(&wanted).elems }
+
+ return @ns.pairs.classify( *.value, :as{.key} ).map({ combin_count(.value) }).sum;
+}
+
+
+constant @n1_1000 = 1 .. 1000; # Best case; no .combinations() at all when no elements are equal.
+constant @n10_100 = |(41..50) xx 100;
+constant @n42_43 = |(42 xx 500), |(43 xx 500);
+constant @n42 = 42 xx 1000; # Worst case; O(N²) when all elements are identical
+use Test; plan +constant @tests =
+ ( 4, 2, (3,1,2,2,2,1,3) ),
+ ( 0, 1, (1,2,3) ),
+
+ ( 0, 2, @n1_1000 ),
+ ( 24750, 2, @n10_100 ),
+ ( 187250, 2, @n42_43 ),
+ ( 374750, 2, @n42 ),
+ ( 1000*999/2, 1, @n42 ),
+;
+for @tests -> ( $expected, $k, @in ) {
+ is task2( $k, @in ), $expected;
+}