aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLuca Ferrari <fluca1978@gmail.com>2020-08-24 14:15:46 +0200
committerLuca Ferrari <fluca1978@gmail.com>2020-08-24 14:15:46 +0200
commit3b7b3ffadd94eb8372845044cde2fcf34b30afa5 (patch)
treebeeb5f541fe8fa45188113c338a7fdbe6755be4c
parentab2670bec6b5a091b61b3d3a6f6211cefa68a425 (diff)
downloadperlweeklychallenge-club-3b7b3ffadd94eb8372845044cde2fcf34b30afa5.tar.gz
perlweeklychallenge-club-3b7b3ffadd94eb8372845044cde2fcf34b30afa5.tar.bz2
perlweeklychallenge-club-3b7b3ffadd94eb8372845044cde2fcf34b30afa5.zip
Task 1 done.
-rw-r--r--challenge-075/luca-ferrari/raku/ch-1.p681
1 files changed, 81 insertions, 0 deletions
diff --git a/challenge-075/luca-ferrari/raku/ch-1.p6 b/challenge-075/luca-ferrari/raku/ch-1.p6
new file mode 100644
index 0000000000..b52a91d40c
--- /dev/null
+++ b/challenge-075/luca-ferrari/raku/ch-1.p6
@@ -0,0 +1,81 @@
+#!raku
+
+sub find-solutions( Int :$sum, :@coins ) {
+ my @solutions;
+
+ # add all the 'one coin' solutions
+ @solutions.push: [ $_ xx ( $sum / $_ ) ] for @coins.grep( $sum %% * );
+
+
+ # now inspect all the other cases
+ for @coins.grep( $sum !%% * ).sort( { $^b <=> $^a } ) -> $current-coin {
+ next if $current-coin > $sum;
+ my @current-solution;
+ @current-solution.push: $current-coin;
+
+ for @coins.grep( * !~~ $current-coin ).sort( { $^b <=> $^a } ) {
+ my $current-sum = [+] @current-solution;
+ # try to add the same number over and over again
+ while ( ( $current-sum + $_ ) <= $sum ) {
+ @current-solution.push: $_ ;
+ $current-sum = [+] @current-solution;
+ }
+
+ if ( $current-sum == $sum ) {
+ # use a new array to clone it, so I can delete the last value and continue over
+ @solutions.push: Array.new: @current-solution.sort;
+ @current-solution[ *-1 ]:delete;
+ next;
+ }
+ }
+
+ }
+
+
+ # last step: decompose every number in a solution into other numbers
+ my @decomposed-solutions;
+ for @solutions -> @current-solution {
+ for 0 ..^ @current-solution.elems -> $switching-index {
+
+ my $current-coin = @current-solution[ $switching-index ];
+ next if $current-coin ~~ 1;
+
+ for @coins.grep( $current-coin %% * ) {
+ next if $_ ~~ $current-coin;
+ my @new-solution = Array.new: @current-solution;
+ @new-solution[ $switching-index ]:delete;
+ @new-solution[ $switching-index ] = | ( $_ xx ( $current-coin / $_ ) );
+ @decomposed-solutions.push: [ @new-solution.sort ];
+ }
+ }
+ }
+
+
+ # now build something unique
+ my %unique-solutions;
+ for @decomposed-solutions {
+ %unique-solutions{ "{ $_ }" } = $_;
+ }
+
+ for @solutions {
+ %unique-solutions{ "{ $_ }" } = $_;
+ }
+
+
+ %unique-solutions.values;
+}
+
+
+
+
+sub MAIN( Int $S where { $S > 0 },
+ *@C where { @C.grep( * ~~ Int ).elems == @C.elems } ) {
+ say "Coins are { @C } that must give sum $S";
+
+ my @solutions;
+
+ @solutions = find-solutions( coins => @C, sum => $S );
+
+ @solutions.join( "\n" ).say;
+
+}