diff options
| author | Mohammad Sajid Anwar <Mohammad.Anwar@yahoo.com> | 2024-01-21 23:10:51 +0000 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2024-01-21 23:10:51 +0000 |
| commit | 899fd7e7fca7954906336197f81f6bef1b82143e (patch) | |
| tree | 269d38cbd3680afc1a29da033038b13454a22aa7 /challenge-252 | |
| parent | 97d273cfe553ee2311365abcaf05f6342124da20 (diff) | |
| parent | 18906c0e06d68c2efa51608b71772fb1216ea3fa (diff) | |
| download | perlweeklychallenge-club-899fd7e7fca7954906336197f81f6bef1b82143e.tar.gz perlweeklychallenge-club-899fd7e7fca7954906336197f81f6bef1b82143e.tar.bz2 perlweeklychallenge-club-899fd7e7fca7954906336197f81f6bef1b82143e.zip | |
Merge pull request #9438 from adamcrussell/challenge-252
initial commit
Diffstat (limited to 'challenge-252')
| -rw-r--r-- | challenge-252/adam-russell/perl/ch-1.pl | 18 | ||||
| -rw-r--r-- | challenge-252/adam-russell/perl/ch-2.pl | 44 |
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..488877436a --- /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. +## +srand(ord q/TWC/); +sub rand_sum_zero{ + 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; + + |
