aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLuca Ferrari <fluca1978@gmail.com>2020-06-29 13:35:05 +0200
committerLuca Ferrari <fluca1978@gmail.com>2020-06-29 13:35:05 +0200
commite278df37b0c49be8f048866a815aa43a13e0760a (patch)
tree807b5a86ecbe2662be2dae7099349f6706ef0877
parent0ccc8cf05e749451a61254b0ca240fc80b3c7a12 (diff)
downloadperlweeklychallenge-club-e278df37b0c49be8f048866a815aa43a13e0760a.tar.gz
perlweeklychallenge-club-e278df37b0c49be8f048866a815aa43a13e0760a.tar.bz2
perlweeklychallenge-club-e278df37b0c49be8f048866a815aa43a13e0760a.zip
A little better implementation of task 1.
-rw-r--r--challenge-067/luca-ferrari/raku/ch-1.p646
1 files changed, 19 insertions, 27 deletions
diff --git a/challenge-067/luca-ferrari/raku/ch-1.p6 b/challenge-067/luca-ferrari/raku/ch-1.p6
index ae742e4567..f9d123fe1d 100644
--- a/challenge-067/luca-ferrari/raku/ch-1.p6
+++ b/challenge-067/luca-ferrari/raku/ch-1.p6
@@ -9,42 +9,34 @@
sub MAIN( Int :$m where { $m > 2 } = 5,
Int :$n where { $n < $m } = 2 ) {
- # available digits
- my @digits = 1 .. $m;
# found combinations
my @combinations;
- for @digits -> $start {
+ for 0 ..^ $m {
- # build the array of combinations starting with the
- # current digits, place another one that is increased by one
- # so to keep sorting...
- my @combination = $start;
- @combination.push: $start + 1;
+ # cannot get negative numbers!
+ next if $m - $_ < $n;
+ # current combination
+ my @combination;
+ # push the last digit of this combination, for example m=5, n=3 -> 5
+ @combination.push: $m - $_;
- # ... and all an element until I've made the array
- while ( @combination.elems < $n ) {
- @combination.push( @combination[ *-1 ] + 1 );
- }
-
-
- # the last element of the array must be the value
- # I've got as parameter, otherwise iterate
- while ( @combination[ *-1 ] < $m ) {
- # clone the array because I'm going to change it!
- @combinations.push: Array.new( @combination );
+ # fill up the combination with decreasing order
+ @combination.push( @combination[ *-1 ] - 1 ) while ( @combination.elems < $n );
+ # push this initial combination, e.g., 5,4,3
+ @combinations.push: Array.new( @combination.reverse );
- # increase by one every element, so it will be kept in
- # order
- for 1 ..^ @combination.elems {
- @combination[ $_ ] += 1;
- }
+ # now go backwards all the digits until we reach '1' with the last digit
+ # e.g. 5,4,2; 5,4,1
+ while ( @combination[ *-1 ] > 1 ) {
+ @combination[ *-1 ] -= 1;
+ @combinations.push: Array.new( @combination.reverse );
}
-
- @combinations.push: @combination if ( @combination[ *-1 ] == $m );
}
- @combinations.join( ", " ).say;
+
+
+ @combinations.sort.join( ", " ).say;
}