diff options
| author | Mohammad S Anwar <Mohammad.Anwar@yahoo.com> | 2020-12-01 17:36:37 +0000 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2020-12-01 17:36:37 +0000 |
| commit | aadb91cac8478a6071555d6cfcf9b9841132dfae (patch) | |
| tree | 37e24195db196285b7e8adb7831881504f08fc4d | |
| parent | 51d9a302d527e4613083fd45ec73ec8d01c79181 (diff) | |
| parent | 189ab16f2fc1acb6e5e711d7d895caf1973acbf6 (diff) | |
| download | perlweeklychallenge-club-aadb91cac8478a6071555d6cfcf9b9841132dfae.tar.gz perlweeklychallenge-club-aadb91cac8478a6071555d6cfcf9b9841132dfae.tar.bz2 perlweeklychallenge-club-aadb91cac8478a6071555d6cfcf9b9841132dfae.zip | |
Merge pull request #2901 from jo-37/contrib
Solutions to challenge 089
| -rwxr-xr-x | challenge-089/jo-37/perl/ch-1.pl | 20 | ||||
| -rwxr-xr-x | challenge-089/jo-37/perl/ch-2.pl | 36 |
2 files changed, 56 insertions, 0 deletions
diff --git a/challenge-089/jo-37/perl/ch-1.pl b/challenge-089/jo-37/perl/ch-1.pl new file mode 100755 index 0000000000..93510bb801 --- /dev/null +++ b/challenge-089/jo-37/perl/ch-1.pl @@ -0,0 +1,20 @@ +#!/usr/bin/perl + +use Test2::V0; +use Math::Utils 'gcd'; +use List::Util 'reduce'; + +sub gcd_sum { + my $n = shift; + reduce { + local *_ = \$b; + $a + reduce {$a + gcd($_, $_ + $b)} 0 .. $n - $b; + } 0 .. $n - 1; +} + +is gcd_sum(3), 3, 'Example 1'; +is gcd_sum(4), 7, 'Example 2'; +is gcd_sum(5), 11; +is gcd_sum(6), 20; + +done_testing; diff --git a/challenge-089/jo-37/perl/ch-2.pl b/challenge-089/jo-37/perl/ch-2.pl new file mode 100755 index 0000000000..b08d40b377 --- /dev/null +++ b/challenge-089/jo-37/perl/ch-2.pl @@ -0,0 +1,36 @@ +#!/usr/bin/perl + +use 5.012; +use PDL; +use Test2::V0 '!float'; + +# Siamese method to construct an odd order magic square. +# See https://en.wikipedia.org/wiki/Siamese_method +$::verbose = 0; +sub siamese { + my $n = shift; + my $ord = 2 * $n + 1 ; + my $msq = zeroes(long, $ord, $ord)->inplace->setvaltobad(0); + my $idx = long $n, 0; + for my $val (1 .. $ord ** 2) { + $msq->range($idx, 0, 'periodic') .= $val; + say $msq if $::verbose; + $idx += $val % $ord ? long(1, -1) : long(0, 1); + } + # Return order, magic constant and magic square + ($ord, ($ord**3 + $ord) / 2, $msq); +} + +# Create some magic squares and check row, column and diagonal +# sums. +for my $n (1 .. 3) { + my ($ord, $magic, $sq) = siamese $n; + say $sq; + + is $sq->sumover->unpdl, [($magic) x $ord], 'row sums'; + is $sq->xchg(0, 1)->sumover->unpdl, [($magic) x $ord], 'col sums'; + is sum($sq->diagonal(0, 1)), $magic, 'diag sum'; + is sum($sq->slice('-1:0')->diagonal(0, 1)), $magic, 'antidiag sum'; +} + +done_testing; |
