diff options
| author | Jörg Sommrey <28217714+jo-37@users.noreply.github.com> | 2024-07-02 20:38:09 +0200 |
|---|---|---|
| committer | Jörg Sommrey <28217714+jo-37@users.noreply.github.com> | 2024-07-05 14:53:04 +0200 |
| commit | 32af75893141fd94028cad2dc15b18af3dcc42bb (patch) | |
| tree | ee573f4da3537835eeef662baca179d4ec5f6420 | |
| parent | f384737b6467805602da8a1be4c957e0d137778c (diff) | |
| download | perlweeklychallenge-club-32af75893141fd94028cad2dc15b18af3dcc42bb.tar.gz perlweeklychallenge-club-32af75893141fd94028cad2dc15b18af3dcc42bb.tar.bz2 perlweeklychallenge-club-32af75893141fd94028cad2dc15b18af3dcc42bb.zip | |
Solution to task 2
| -rwxr-xr-x | challenge-276/jo-37/perl/ch-2.pl | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/challenge-276/jo-37/perl/ch-2.pl b/challenge-276/jo-37/perl/ch-2.pl new file mode 100755 index 0000000000..40c1c23c22 --- /dev/null +++ b/challenge-276/jo-37/perl/ch-2.pl @@ -0,0 +1,68 @@ +#!/usr/bin/perl -s + +use v5.24; +use Test2::V0; +use List::Util 'reduce'; + +our ($tests, $examples); + +run_tests() if $tests || $examples; # does not return + +die <<EOS unless @ARGV; +usage: $0 [-examples] [-tests] [I...] + +-examples + run the examples from the challenge + +-tests + run some tests + +I... + list of items + +EOS + + +### Input and Output + +say max_freq(@ARGV); + + +### Implementation +# +# For details see: +# https://github.sommrey.de/the-bears-den/2024/07/05/ch-276.html#task-2 + + +sub max_freq { + my ($maxfreq, %freq) = 0; + + reduce { + &{ ( sub {$a + $maxfreq}, + sub {$maxfreq = $freq{$b}}, + sub {$a} + )[++$freq{$b} <=> $maxfreq] + }() + } 0, @_; +} + + +### Examples and tests + +sub run_tests { + SKIP: { + skip "examples" unless $examples; + + is max_freq(1, 2, 2, 4, 1, 5), 4, 'example 1'; + is max_freq(1, 2, 3, 4, 5), 5, 'example 2'; + } + + SKIP: { + skip "tests" unless $tests; + + is max_freq(qw(a b a b c d c d e f e f e c a)), 9, 'non-numbers' + } + + done_testing; + exit; +} |
