aboutsummaryrefslogtreecommitdiff
path: root/challenge-149
diff options
context:
space:
mode:
authorJörg Sommrey <28217714+jo-37@users.noreply.github.com>2022-01-24 15:39:44 +0100
committerJörg Sommrey <28217714+jo-37@users.noreply.github.com>2022-01-27 22:13:34 +0100
commit07f458112db95658b036fc0b03ddd1eff495edfb (patch)
treea1d789f6356f49a22bfb586ca967d76c167321cd /challenge-149
parenteac8ba024f5328cadea77c3088023a99f714bbfb (diff)
downloadperlweeklychallenge-club-07f458112db95658b036fc0b03ddd1eff495edfb.tar.gz
perlweeklychallenge-club-07f458112db95658b036fc0b03ddd1eff495edfb.tar.bz2
perlweeklychallenge-club-07f458112db95658b036fc0b03ddd1eff495edfb.zip
Solution to task 2
Diffstat (limited to 'challenge-149')
-rwxr-xr-xchallenge-149/jo-37/perl/ch-2.pl58
1 files changed, 58 insertions, 0 deletions
diff --git a/challenge-149/jo-37/perl/ch-2.pl b/challenge-149/jo-37/perl/ch-2.pl
new file mode 100755
index 0000000000..20cf301279
--- /dev/null
+++ b/challenge-149/jo-37/perl/ch-2.pl
@@ -0,0 +1,58 @@
+#!/usr/bin/perl -s
+
+use v5.16;
+use Test2::V0;
+use List::AllUtils qw(frequency max pairvalues);
+use Math::Prime::Util qw(fromdigits todigits todigitstring);
+use experimental 'signatures';
+
+our $examples;
+
+run_tests() if $examples; # does not return
+
+die <<EOS unless @ARGV;
+usage: $0 [-examples] [base]
+
+-examples
+ run the examples from the challenge
+
+base
+ Find the largest perfect square having no repeated digits in the
+ given base.
+
+EOS
+
+
+### Input and Output
+
+# Print the largest square in the requested base.
+say todigitstring(max_square($ARGV[0]), $ARGV[0]);
+
+
+### Implementation
+
+# The maximum number having no repeated digits in a given base is the
+# number built from all digits in descending order. Trying all perfect
+# squares down from this maximum.
+#
+# Returns an integer, not the requested string.
+sub max_square ($base) {
+ for (my $r = int sqrt fromdigits [reverse 0 .. $base - 1], $base;; $r--) {
+ my $k = $r ** 2;
+ return $k if 1 == max pairvalues frequency todigits $k, $base;
+ }
+}
+
+
+
+### Examples and tests
+
+sub run_tests {
+ is todigitstring(max_square(2), 2), '1', 'example 1';
+ is todigitstring(max_square(4), 4), '3201', 'example 2';
+ is max_square(10), 9814072356, 'example 3';
+ like todigitstring(max_square(12), 12), qr/^B8750A649321$/i, 'example 4';
+
+ done_testing;
+ exit;
+}