diff options
| author | Jörg Sommrey <28217714+jo-37@users.noreply.github.com> | 2024-02-26 22:12:44 +0100 |
|---|---|---|
| committer | Jörg Sommrey <28217714+jo-37@users.noreply.github.com> | 2024-03-01 15:16:15 +0100 |
| commit | 99ef47a429fb0c7e44183e4c0e2f9febeb4a8e05 (patch) | |
| tree | b059e703cacdb20a56132c9933b4109c3a3d3581 | |
| parent | 7570e857351225497f3b92034be0fc7155c10db1 (diff) | |
| download | perlweeklychallenge-club-99ef47a429fb0c7e44183e4c0e2f9febeb4a8e05.tar.gz perlweeklychallenge-club-99ef47a429fb0c7e44183e4c0e2f9febeb4a8e05.tar.bz2 perlweeklychallenge-club-99ef47a429fb0c7e44183e4c0e2f9febeb4a8e05.zip | |
Solution to task 2
| -rwxr-xr-x | challenge-258/jo-37/perl/ch-2.pl | 60 |
1 files changed, 60 insertions, 0 deletions
diff --git a/challenge-258/jo-37/perl/ch-2.pl b/challenge-258/jo-37/perl/ch-2.pl new file mode 100755 index 0000000000..c9bf4e62d7 --- /dev/null +++ b/challenge-258/jo-37/perl/ch-2.pl @@ -0,0 +1,60 @@ +#!/usr/bin/perl -s + +use v5.24; +use Test2::V0; +use List::Util 'sum0'; + +our ($tests, $examples, $bits); + +run_tests() if $tests || $examples; # does not return + +die <<EOS unless defined $bits and @ARGV; +usage: $0 [-examples] [-tests] [-bits=K] [N...] + +-examples + run the examples from the challenge + +-tests + run some tests + +-bits=K + sum over numbers with a k-bit index + +N... + list of numbers + +EOS + + +### Input and Output + +say k_bit_sum($bits, @ARGV); + + +### Implementation + +sub k_bit_sum { + my $k = shift; + + sum0 @_[grep unpack('%32b*', pack('l', $_)) == $k, 0 .. $#_]; +} + + +### Examples and tests + +sub run_tests { + SKIP: { + skip "examples" unless $examples; + + is k_bit_sum(1 ,=> 2, 5, 9, 11, 3), 17, 'example 1'; + is k_bit_sum(2 ,=> 2, 5, 9, 11, 3), 11, 'example 2'; + is k_bit_sum(0 ,=> 2, 5, 9, 11, 3), 2, 'example 3'; + } + + SKIP: { + skip "tests" unless $tests; + } + + done_testing; + exit; +} |
