Knapsack problem/Continuous: Difference between revisions
m
→{{header|Perl 6}}: fixed 'new' method
mNo edit summary |
SqrtNegInf (talk | contribs) m (→{{header|Perl 6}}: fixed 'new' method) |
||
Line 2,062:
Output is the same as for version 1.
=={{header|Perl 6}}==
{{Works with|rakudo|2016.08}}
This Solutions sorts the item by WEIGHT/VALUE
<lang perl6>class KnapsackItem {
[qw'beef 3.8 36'],▼
has $.name;
has $.weight is rw;
[qw'ham 3.6 90'],▼
has $.price is rw;
[qw'greaves 2.4 45'],▼
has $.ppw;
[qw'flitch 4.0 30'],▼
[qw'brawn 2.5 56'],▼
[qw'welt 3.7 67'],▼
[qw'salami 3.0 95'],▼
[qw'sausage 5.9 98'],▼
method new (Str $n, Rat $w, Int $p) {
self.bless(:name($n), :weight($w), :price($p), :ppw($w/$p))
}
method cut-maybe ($max-weight) {
return False if $max-weight > $.weight;
$.weight = $.ppw *
return True;
}
$limit -= $_->[1];▼
method gist () { sprintf "%8s %1.2f %3.2f",
}▼
}
my $max-w = 15;
say "Item Portion Value";
</lang>▼
.say for gather
==> map({ KnapsackItem.new($^a, $^b, $^c) })
==> sort *.ppw
{
my $last-one = .cut-maybe($max-w);
last if $last-one;
▲ }</lang>
'''Output:'''
<pre>
%perl6 knapsack_continous.p6
Item Portion Value
ham 3.60 90.00
welt 3.50 63.38
</pre>
|