aboutsummaryrefslogtreecommitdiff
path: root/challenge-252
diff options
context:
space:
mode:
authorUtil <bruce.gray@acm.org>2024-01-21 14:15:23 -0600
committerUtil <bruce.gray@acm.org>2024-01-21 14:15:23 -0600
commita352d0b7e202360d808e9fb0f35c70db907f6467 (patch)
treee805c3563aa11848276a2a54d84cdb277061f4b6 /challenge-252
parent7dec4547065d2c85daf9bfdfdebe21f87dd23e84 (diff)
downloadperlweeklychallenge-club-a352d0b7e202360d808e9fb0f35c70db907f6467.tar.gz
perlweeklychallenge-club-a352d0b7e202360d808e9fb0f35c70db907f6467.tar.bz2
perlweeklychallenge-club-a352d0b7e202360d808e9fb0f35c70db907f6467.zip
Add TWC 252 solutions by Bruce Gray (in Raku only).
Diffstat (limited to 'challenge-252')
-rw-r--r--challenge-252/bruce-gray/raku/ch-1.raku21
-rw-r--r--challenge-252/bruce-gray/raku/ch-2.raku32
2 files changed, 53 insertions, 0 deletions
diff --git a/challenge-252/bruce-gray/raku/ch-1.raku b/challenge-252/bruce-gray/raku/ch-1.raku
new file mode 100644
index 0000000000..758d93f280
--- /dev/null
+++ b/challenge-252/bruce-gray/raku/ch-1.raku
@@ -0,0 +1,21 @@
+sub sum_of_squares ( @a --> UInt ) { @a»².sum }
+
+sub special_elements ( @a ) {
+ # An array element is "special" if its 1-based index
+ # evenly divides into the array size.
+ return @a.grep({ @a %% ++$ });
+}
+
+sub task1 ( @ns --> UInt ) {
+ return sum_of_squares special_elements @ns;
+}
+
+
+my @tests =
+ ( 21, (1, 2, 3, 4) ),
+ ( 63, (2, 7, 1, 19, 18, 3) ),
+;
+use Test; plan +@tests;
+for @tests -> ( $expected, @in ) {
+ is task1(@in), $expected;
+}
diff --git a/challenge-252/bruce-gray/raku/ch-2.raku b/challenge-252/bruce-gray/raku/ch-2.raku
new file mode 100644
index 0000000000..6a88fe477f
--- /dev/null
+++ b/challenge-252/bruce-gray/raku/ch-2.raku
@@ -0,0 +1,32 @@
+sub task2 ( UInt $n ) {
+ return ($n - $n²) div 2, |( 1 ..^ $n );
+}
+sub matches_task_specification ( UInt $n, @got --> Bool ) {
+ # Array of _$n_ _unique_ _integers_ that _sum_ to _zero_.
+ return False if @got.elems !== $n;
+ return False if @got.repeated !== 0;
+ return False if @got.any !~~ Int;
+ return False if @got.sum !== 0;
+ return True;
+}
+
+
+# Many solutions to every $n except $n==1,
+# so we cannot use the output from the task examples.
+### my @tests =
+### # Two other possible solutions could be as below: (-5, -1, 1, 2, 3) and (-3, -1, 2, -2, 4).
+### ( 5, (-7, -1, 1, 3, 4) ),
+### ( 3, (-1, 0, 1) ),
+### ( 1, (0,) ),
+### ;
+use Test; plan 1;
+constant $test_range = 1 .. 1_000;
+my $fails = 0;
+for $test_range -> $n {
+ my @got = task2($n);
+ if ! matches_task_specification($n, @got) {
+ note "Failed: $n => @got[]";
+ $fails++;
+ }
+}
+is $fails, 0, "No failures when testing {$test_range.raku}";