diff options
| author | Mohammad S Anwar <Mohammad.Anwar@yahoo.com> | 2023-01-29 10:34:24 +0000 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2023-01-29 10:34:24 +0000 |
| commit | 5cfdb5571b9fd0432797bb8483799de7fbb0d827 (patch) | |
| tree | b1c572198b2d0cc9386fae05acca9f53b6b6b296 /challenge-201/peter-campbell-smith/perl/ch-2.pl | |
| parent | 7cc22bf5e84b1ad7199db54621bd525faa898be9 (diff) | |
| parent | 765adc7879be15d547a1cec11b022d46a330be8f (diff) | |
| download | perlweeklychallenge-club-5cfdb5571b9fd0432797bb8483799de7fbb0d827.tar.gz perlweeklychallenge-club-5cfdb5571b9fd0432797bb8483799de7fbb0d827.tar.bz2 perlweeklychallenge-club-5cfdb5571b9fd0432797bb8483799de7fbb0d827.zip | |
Merge pull request #7459 from pjcs00/wk201
week 201 submission
Diffstat (limited to 'challenge-201/peter-campbell-smith/perl/ch-2.pl')
| -rwxr-xr-x | challenge-201/peter-campbell-smith/perl/ch-2.pl | 52 |
1 files changed, 52 insertions, 0 deletions
diff --git a/challenge-201/peter-campbell-smith/perl/ch-2.pl b/challenge-201/peter-campbell-smith/perl/ch-2.pl new file mode 100755 index 0000000000..4596c64cb8 --- /dev/null +++ b/challenge-201/peter-campbell-smith/perl/ch-2.pl @@ -0,0 +1,52 @@ +#!/usr/bin/perl + +# Peter Campbell Smith - 2023-01-23 +# PWC 201 task 2 + +use v5.28; +use utf8; +use warnings; + +# Task: You are given an integer, $n > 0. Write a script to determine the number of ways of putting $n +# pennies in a row of piles such that each pile contains no fewer pennies than the one on its left. + +# Blog: https://pjcs-pwc.blogspot.com/2023/01/201-missing-numbers-and-piles-of-pennies.html + +my (@tests, $n, $ways, $piles); + +@tests = (1, 2, 3, 4, 5, 20); + +# loop over tests +for $n (@tests) { + + # initialise + $ways = 0; + $piles = ''; + + # find possible ways to do it + find_ways($n, $n, ''); + + # output results + say qq[Input: \$n = $n\nOutput: ] . $ways; + say qq[Piles:\n$piles]; +} + +sub find_ways { + + # returns the number of possible ways of stacking $pennies pennies in stacks no more than $height + my ($pennies, $height, $stack) = @_; + my ($h); + + # no pennies left - answer found + if ($pennies == 0) { + $piles .= qq[$stack\n]; + $stack = ''; + $ways ++; + return; + } + + # loop over possible piles + for $h (1 .. ($pennies > $height ? $height : $pennies)) { + find_ways($pennies - $h, $h, qq[$h $stack]); + } +} |
