aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAdam Russell <ac.russell@live.com>2024-01-21 17:33:11 -0500
committerAdam Russell <ac.russell@live.com>2024-01-21 17:33:11 -0500
commit86ed7e9f7fe4e19919a836752e7582c8c9bb1799 (patch)
tree8cd313890516b9a6ef334ccaec9f8346cf42e7d1
parent7efb373bb9adffa79f84825217015835805298b5 (diff)
downloadperlweeklychallenge-club-86ed7e9f7fe4e19919a836752e7582c8c9bb1799.tar.gz
perlweeklychallenge-club-86ed7e9f7fe4e19919a836752e7582c8c9bb1799.tar.bz2
perlweeklychallenge-club-86ed7e9f7fe4e19919a836752e7582c8c9bb1799.zip
initial commit
-rw-r--r--challenge-252/adam-russell/perl/ch-1.pl18
-rw-r--r--challenge-252/adam-russell/perl/ch-2.pl44
2 files changed, 62 insertions, 0 deletions
diff --git a/challenge-252/adam-russell/perl/ch-1.pl b/challenge-252/adam-russell/perl/ch-1.pl
new file mode 100644
index 0000000000..73f9b0825c
--- /dev/null
+++ b/challenge-252/adam-russell/perl/ch-1.pl
@@ -0,0 +1,18 @@
+use v5.38;
+##
+# Given an array of integers, @ints write a script to find the sum of
+# the squares of all special elements of the given array.
+# An element $int[i] of @ints is called special if i divides n,
+# where n is the length of the given array. Consider the array to be
+# 1-indexed for this task.
+##
+sub special_numbers{
+ my $r;
+ do{
+ $r += $_[$_] * $_[$_] if @_ % ($_ + 1) == 0;
+ } for 0 .. @_ - 1;
+ return $r;
+}
+
+say special_numbers 1, 2, 3, 4;
+say special_numbers 2, 7, 1, 19, 18, 3;
diff --git a/challenge-252/adam-russell/perl/ch-2.pl b/challenge-252/adam-russell/perl/ch-2.pl
new file mode 100644
index 0000000000..92893abfa7
--- /dev/null
+++ b/challenge-252/adam-russell/perl/ch-2.pl
@@ -0,0 +1,44 @@
+use v5.38;
+##
+# Given an integer, $n, write a script to find an array containing $n
+# unique integers such that they add up to zero.
+##
+sub rand_sum_zero{
+ srand(ord q/TWC/);
+ my $n = shift;
+ my @r;
+ my $x = int(rand($n * 5)) + 1;
+ return $x, -$x if $n == 2;
+ my $r;
+ {
+ $r = int(rand($x - 1)) + 1;
+ $r *= -1 if rand() < 0.5;
+ redo if $x + $r < $n || $x == 0;
+ #$r = $x - $r;
+ }
+ my $s = $x + $r;
+ push @r, $x, $r;
+ while(@r < $n - 1){
+ {
+ $r = int(rand($r - 1)) + 1;
+ $r *= -1 if rand() < 0.5;
+ redo if (0 != grep {$_ == $r} @r) || $s + $r < $n || $x == 0;
+ }
+ $s += $r;
+ push @r, $r;
+ }
+ push @r, -$s if @r == $n - 1;
+ return @r;
+}
+
+sub unique_sum_zero{
+ my $n = shift;
+ return 0 if $n == 1;
+ return rand_sum_zero $n if $n >= 2;
+}
+
+say join q/,/, unique_sum_zero 1;
+say join q/,/, unique_sum_zero 3;
+say join q/,/, unique_sum_zero 5;
+
+