diff options
| author | Jörg Sommrey <28217714+jo-37@users.noreply.github.com> | 2020-06-15 14:35:32 +0200 |
|---|---|---|
| committer | Jörg Sommrey <28217714+jo-37@users.noreply.github.com> | 2020-06-18 22:13:10 +0200 |
| commit | 9979454fd9e2e0ed31b1f1a3a36decabaa41b786 (patch) | |
| tree | 44afc94ad9105cc41d6b33e03e98c5aa7d75eec3 /challenge-065 | |
| parent | 43654d04824a47db728bdbcf61bf319126d7d9d4 (diff) | |
| download | perlweeklychallenge-club-9979454fd9e2e0ed31b1f1a3a36decabaa41b786.tar.gz perlweeklychallenge-club-9979454fd9e2e0ed31b1f1a3a36decabaa41b786.tar.bz2 perlweeklychallenge-club-9979454fd9e2e0ed31b1f1a3a36decabaa41b786.zip | |
solution for ch-1
Diffstat (limited to 'challenge-065')
| -rw-r--r-- | challenge-065/jo-37/perl/ch-1.pl | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/challenge-065/jo-37/perl/ch-1.pl b/challenge-065/jo-37/perl/ch-1.pl new file mode 100644 index 0000000000..a2c6df1643 --- /dev/null +++ b/challenge-065/jo-37/perl/ch-1.pl @@ -0,0 +1,36 @@ +#!/usr/bin/perl + +use Test2::V0; +use List::Util qw(min max); + +# Calculates all numbers of a given length with the given +# digit sum. +# For every possible first digit the following digits are +# retrieved by recursing into the same sub with reduced +# length and sum. +# A leading zero is allowed when the third parameter is true. +sub digit_sum; +sub digit_sum { + my ($length, $sum, $leading_zero) = @_; + + return if $sum > 9 * $length; + return $sum if $length == 1; + + my $min = max !$leading_zero, $sum - 9 * ($length - 1); + my $max = min 9, $sum; + + map { + my $d = $_; + map $d . $_, digit_sum $length - 1, $sum - $d, 1; + } ($min .. $max); +} + +is [digit_sum 2, 4], [13, 22, 31, 40], 'Example from challenge'; +is [digit_sum 4, 3], + [1002, 1011, 1020, 1101, 1110, 1200, 2001, 2010, 2100, 3000], + 'Another example'; +is [digit_sum 2, 11], + [29, 38, 47, 56, 65, 74, 83, 92], 'digit sum greater than 9'; +is [digit_sum 1, 10], [], 'no solution'; + +done_testing; |
