diff options
| author | Jörg Sommrey <28217714+jo-37@users.noreply.github.com> | 2023-11-20 19:34:25 +0100 |
|---|---|---|
| committer | Jörg Sommrey <28217714+jo-37@users.noreply.github.com> | 2023-11-24 15:40:53 +0100 |
| commit | 6098b55bf66ef842c1afe1eeb68a46f85f34cc0c (patch) | |
| tree | 6bfd30c0762e728665807ba2dd77f6ea4375d8c9 | |
| parent | 3b5b82a83e72faf87a8ba4da7fe26ffffd813c3a (diff) | |
| download | perlweeklychallenge-club-6098b55bf66ef842c1afe1eeb68a46f85f34cc0c.tar.gz perlweeklychallenge-club-6098b55bf66ef842c1afe1eeb68a46f85f34cc0c.tar.bz2 perlweeklychallenge-club-6098b55bf66ef842c1afe1eeb68a46f85f34cc0c.zip | |
Solution to task 2
| -rwxr-xr-x | challenge-244/jo-37/perl/ch-2.pl | 65 |
1 files changed, 65 insertions, 0 deletions
diff --git a/challenge-244/jo-37/perl/ch-2.pl b/challenge-244/jo-37/perl/ch-2.pl new file mode 100755 index 0000000000..4a51d8fba7 --- /dev/null +++ b/challenge-244/jo-37/perl/ch-2.pl @@ -0,0 +1,65 @@ +#!/usr/bin/perl -s + +use v5.16; +use Test2::V0; +use bigint; + +our ($tests, $examples); + +run_tests() if $tests || $examples; # does not return + +die <<EOS unless @ARGV; +usage: $0 [-examples] [-tests] [N...] + +-examples + run the examples from the challenge + +-tests + run some tests + +N... + list of numbers + +EOS + + +### Input and Output + +say total_power(@ARGV); + + +### Implementation + +sub total_power { + my @s = sort {$a <=> $b} @_; + my $power; + while (defined (my $min = $s[0])) { + while (my ($offs, $max) = each @s) { + $power += $min * $max**2 * ($offs ? 2**($offs - 1) : 1); + } + } continue { + shift @s; + } + + $power; +} + +### Examples and tests + +sub run_tests { + SKIP: { + skip "examples" unless $examples; + + is total_power(2, 1, 4), 141, 'example 1'; + } + + SKIP: { + + is total_power(2, 3, 5, 7), 1627, 'example from blog'; + is total_power((2) x 64), (2**64 - 1) * 2 * 2**2, + '147573952589676412920'; + } + + done_testing; + exit; +} |
