diff options
| author | Mohammad Sajid Anwar <Mohammad.Anwar@yahoo.com> | 2023-10-15 09:31:38 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2023-10-15 09:31:38 +0100 |
| commit | 4bbde24e3d663c412acc249855f7689e405b9c7b (patch) | |
| tree | 667ae8e8eb90ca669a0ff4a300e983269af2d094 | |
| parent | 381e23acd11cfb8fd05471b896f05d58e8f04836 (diff) | |
| parent | 15d5a82792294c7c51c39537722f6a4b8475509b (diff) | |
| download | perlweeklychallenge-club-4bbde24e3d663c412acc249855f7689e405b9c7b.tar.gz perlweeklychallenge-club-4bbde24e3d663c412acc249855f7689e405b9c7b.tar.bz2 perlweeklychallenge-club-4bbde24e3d663c412acc249855f7689e405b9c7b.zip | |
Merge pull request #8864 from kjetillll/challenge-238-kjetillll
https://theweeklychallenge.org/blog/perl-weekly-challenge-238/
| -rw-r--r-- | challenge-238/kjetillll/perl/ch-1.pl | 29 | ||||
| -rw-r--r-- | challenge-238/kjetillll/perl/ch-2.pl | 37 |
2 files changed, 66 insertions, 0 deletions
diff --git a/challenge-238/kjetillll/perl/ch-1.pl b/challenge-238/kjetillll/perl/ch-1.pl new file mode 100644 index 0000000000..6e2a1dbf14 --- /dev/null +++ b/challenge-238/kjetillll/perl/ch-1.pl @@ -0,0 +1,29 @@ +#!/usr/bin/perl +use strict; use warnings; + +sub running_sum { + my($first,@rest)=@_; + @rest ? do{ $rest[0]+=$first; $first, running_sum(@rest) } + : $first +} + +@ARGV ? run_args(@ARGV) + : run_tests(); + +sub run_args { + print "@{[ &running_sum ]}\n" +} + +sub run_tests { + for my $test ( + [ [1, 2, 3, 4, 5], => [1, 3, 6, 10, 15] ], + [ [1, 1, 1, 1, 1], => [1, 2, 3, 4, 5] ], + [ [0, -1, 1, 2], => [0, -1, 0, 2 ] ] + ){ + my($input,$expected)=@$test; + my @got = running_sum(@$input); + print "@$expected" eq "@got" ? 'ok' : '***NOT OK'; + print " input: @$input expected: @$expected got: @got\n"; + } +} + diff --git a/challenge-238/kjetillll/perl/ch-2.pl b/challenge-238/kjetillll/perl/ch-2.pl new file mode 100644 index 0000000000..1a5bd15d78 --- /dev/null +++ b/challenge-238/kjetillll/perl/ch-2.pl @@ -0,0 +1,37 @@ +#!/usr/bin/perl +use strict; use warnings; + +sub steps { + my $n=pop; + my @digits=$n=~/\d/g; + my $p=eval join'*', @digits; + $p>9?1+steps($p):1 +} + +sub sort_persistence { + map $$_{value}, + sort { $$a{steps}<=>$$b{steps} or + $$a{value}<=>$$b{value} } + map{ {steps=>steps($_), value=>$_} } + @_ +} + +@ARGV ? run_args(@ARGV) + : run_tests(); + +sub run_args { + print "@{[ &sort_persistence ]}\n" +} + +sub run_tests { + for my $test ( + [ [15, 99, 1, 34] => [1, 15, 34, 99] ], + [ [50, 25, 33, 22] => [22, 33, 50, 25] ], + ){ + my($input,$expected)=@$test; + my @got = sort_persistence(@$input); + print "@$expected" eq "@got" ? 'ok' : '***NOT OK'; + print " input: @$input expected: @$expected got: @got\n"; + } +} + |
