diff options
| author | Simon Proctor <simon.proctor@zpg.co.uk> | 2019-11-26 10:10:18 +0000 |
|---|---|---|
| committer | Simon Proctor <simon.proctor@zpg.co.uk> | 2019-11-26 10:10:18 +0000 |
| commit | 42f02aa1199310f6ca041da4e92ffa1139d0534c (patch) | |
| tree | 98a89c3e1f47471a4bfb4dcf0218bcc5204ed8e0 /challenge-036/simon-proctor/perl6 | |
| parent | c17278b3f7ea185f76bd602895199bb3f188d28a (diff) | |
| download | perlweeklychallenge-club-42f02aa1199310f6ca041da4e92ffa1139d0534c.tar.gz perlweeklychallenge-club-42f02aa1199310f6ca041da4e92ffa1139d0534c.tar.bz2 perlweeklychallenge-club-42f02aa1199310f6ca041da4e92ffa1139d0534c.zip | |
Knapsack problem
Diffstat (limited to 'challenge-036/simon-proctor/perl6')
| -rw-r--r-- | challenge-036/simon-proctor/perl6/ch-2.p6 | 30 |
1 files changed, 30 insertions, 0 deletions
diff --git a/challenge-036/simon-proctor/perl6/ch-2.p6 b/challenge-036/simon-proctor/perl6/ch-2.p6 new file mode 100644 index 0000000000..efc64657cb --- /dev/null +++ b/challenge-036/simon-proctor/perl6/ch-2.p6 @@ -0,0 +1,30 @@ +#!/usr/bin/env perl6 + +use v6; + +class Box { + has Int $.weight; + has Int $.worth; + + method gist { "{$!weight}kg worth £{$!worth}" } +} + +#| Calculate the most valuable boxes you can carry +sub MAIN( + Int $max-boxes = 5, #= Max number of boxes you can carry (default 5) + Int $max-weight = 15, #= Max weight of boxes you can carry (default 15kg) +) { + my @boxes = ( Box.new( :1weight, :1worth ), + Box.new( :1weight, :2worth ), + Box.new( :2weight, :2worth ), + Box.new( :12weight, :4worth ), + Box.new( :4weight, :10worth ) ); + + say "I can take up to {$max-boxes} boxes weighing up to {$max-weight}kg from this selection"; + .say for @boxes; + + my @options = @boxes.combinations().grep( *.elems <= $max-boxes ).grep( { ([+] $_.map( *.weight )) <= $max-weight } ).sort( { ( [+] $^b.map( *.worth ) ) cmp ( [+] $^a.map( *.worth ) ) } ); + + say "I think I'll take :"; + .say for @options[0].list; +} |
