diff options
| author | Jörg Sommrey <28217714+jo-37@users.noreply.github.com> | 2022-05-03 14:23:43 +0200 |
|---|---|---|
| committer | Jörg Sommrey <28217714+jo-37@users.noreply.github.com> | 2022-05-04 21:10:28 +0200 |
| commit | fe3f63d53074a27740ac314212da59eb4b1fbf8e (patch) | |
| tree | da299d1d210ff0cf9d88f50ea1475fff54a068fd /challenge-163 | |
| parent | 8450f8839063870ddad1911c3b2f7d3724fdba24 (diff) | |
| download | perlweeklychallenge-club-fe3f63d53074a27740ac314212da59eb4b1fbf8e.tar.gz perlweeklychallenge-club-fe3f63d53074a27740ac314212da59eb4b1fbf8e.tar.bz2 perlweeklychallenge-club-fe3f63d53074a27740ac314212da59eb4b1fbf8e.zip | |
Solution to task 2
Diffstat (limited to 'challenge-163')
| -rwxr-xr-x | challenge-163/jo-37/perl/ch-2.pl | 50 |
1 files changed, 50 insertions, 0 deletions
diff --git a/challenge-163/jo-37/perl/ch-2.pl b/challenge-163/jo-37/perl/ch-2.pl new file mode 100755 index 0000000000..fbf230e7c9 --- /dev/null +++ b/challenge-163/jo-37/perl/ch-2.pl @@ -0,0 +1,50 @@ +#!/usr/bin/perl -s + +use v5.16; +use Test2::V0; +use List::Util 'reductions'; +use experimental 'signatures'; + +our $examples; + +run_tests() if $examples; # does not return + +die <<EOS unless @ARGV; +usage: $0 [-examples] [N...] + +-examples + run the examples from the challenge + +N... + Calculate the "triangular sum" over the given numbers. + +EOS + + +### Input and Output + +say triangular_sum(@ARGV); + + +### Implementation + +sub triangular_sum (@n) { + # Calculate the running sums over the array starting with the second + # element until the array becomes a singleton. + @n = reductions {$a + $b} @n[1 .. $#n] while @n > 1; + + $n[0]; +} + + +### Examples and tests + +sub run_tests { + + # Meeting Slartibartfast, again. + is triangular_sum(1, 2, 3, 4, 5), 42, 'example 1'; + is triangular_sum(1, 3, 5, 7, 9), 70, 'example 2'; + + done_testing; + exit; +} |
