diff options
| author | Luca Ferrari <fluca1978@gmail.com> | 2021-05-10 14:52:06 +0200 |
|---|---|---|
| committer | Luca Ferrari <fluca1978@gmail.com> | 2021-05-10 14:52:06 +0200 |
| commit | a2bd10bd016a727da31e7c123b345055de8ce6cb (patch) | |
| tree | b65722b51e729fe273e3661f39a2ff4a6ca04d9a | |
| parent | 7e9b47b213406af755cff749ab520df133cff255 (diff) | |
| download | perlweeklychallenge-club-a2bd10bd016a727da31e7c123b345055de8ce6cb.tar.gz perlweeklychallenge-club-a2bd10bd016a727da31e7c123b345055de8ce6cb.tar.bz2 perlweeklychallenge-club-a2bd10bd016a727da31e7c123b345055de8ce6cb.zip | |
Better implementation of task 2.
| -rw-r--r-- | challenge-112/luca-ferrari/raku/ch-2.p6 | 56 |
1 files changed, 13 insertions, 43 deletions
diff --git a/challenge-112/luca-ferrari/raku/ch-2.p6 b/challenge-112/luca-ferrari/raku/ch-2.p6 index 7b37b0b587..c735eb0a1a 100644 --- a/challenge-112/luca-ferrari/raku/ch-2.p6 +++ b/challenge-112/luca-ferrari/raku/ch-2.p6 @@ -1,56 +1,26 @@ #!raku sub MAIN( Int $top where { $top > 1 } ) { - # my @haystack = (1 xx $top, 2 xx $top / 2).flat; - # my @solutions; - - # # get all possible combinations - # for @haystack.permutations { - # # check every sub-array that gives me the sum - # for 0 ..^ $_.elems -> $index { - # @solutions.push: $_[ 0 .. $index ] if $_[ 0 .. $index ].sum == $top; - # } - # } - - - - # my @solutions; - # my @haystack = 1,2; - - # my @current-solution; - # while ( @current-solution.sum < $top ) { - # if @current-solution.sum + @haystack[ 1 ] <= $top { - # @current-solution.push: @haystack [ 1 ]; - # } - # elsif @current-solution.sum + @haystack[ 0 ] <= $top { - # @current-solution.push: @haystack [ 0 ]; - # } - # } - - my @solutions; @solutions.push: 1 xx $top; - @solutions.push: 2 xx $top / 2 if $top %% 2; - - my @current-solution; - while ( @current-solution.sum != $top ) { - @current-solution.push: 2 if @current-solution.sum + 2 <= $top; - @current-solution.push: 1 if @current-solution.sum + 1 <= $top; - } - if @current-solution.sum == $top { - @solutions.push: $_ for @current-solution.permutations + my $current-solution = 1 x $top; + while ( $current-solution ~~ / 1 ** 2 / ) { + $current-solution ~~ s/ 1 ** 2 / 2 /; + $current-solution = $current-solution.split( ' ', :skip-empty ).join( '' ); + @solutions.push: $_ for $current-solution.split( '', :skip-empty ).permutations.unique( as => { .Str.trim } ); + + } - - # print only unique values - for @solutions.unique( as => { .Str } ) -> @current-solution { - say ""; - "%d step%s ".sprintf( $_, $_ > 1 ?? 's' !! '' ).print for @current-solution; - say ""; + for @solutions -> @current-solution { + say "\nPossible solution:"; + "%d step%s ".sprintf( $_, $_ > 1 ?? 's' !! '' ).print if $_ > 0 for @current-solution; + } - + + say ""; } |
