Knapsack problem/Continuous: Difference between revisions

→‎{{header|Perl 6}}: reformat for style and clarity
m (→‎{{header|D}}: minor change)
(→‎{{header|Perl 6}}: reformat for style and clarity)
Line 704:
=={{header|Perl 6}}==
This Solutions sorts the item by WEIGHT/VALUE
<lang perl6>class KnapsackItem {
has ($.name, $.weight is rw,$.price is rw, $.ppw);
has $.weight =is .ppw * .pricerw;
method new (Str $n, $w, $p){
has $.price is rw;
KnapsackItem.bless(*, :name($n), :weight($w), :price($p), :ppw($w/$p))
has $.ppw;
}
 
method cut_maybenew (Str $_:n, $max_weightw, $p) {
KnapsackItem.bless(*, :name($n), :weight($w), :price($p), :ppw($w/$p))
return False if $max_weight > .weight;
}
.price = (1/.ppw) * $max_weight;
.weight = .ppw * .price;
return True;
}
 
method cut-maybe ($max-weight) {
method Str ($_:){sprintf "%8s %1.2f %3.2f",.name, .weight, .price}
return False if $max_weightmax-weight > $.weight;
};
$.price = $max-weight / $.ppw;
$.priceweight = (1/$.ppw) * $max_weight.price;
return True;
}
 
method Str ($_:) { sprintf "%8s %1.2f %3.2f",.name, .weight, .price}
my $max_w = 15;
$.name,
$.weight,
$.price }
}
 
my $max_wmax-w = 15;
say "Item Portion Value";
 
.say for gather for
for < beef 3.8 36
pork 5.4 43
ham 3.6 90
greaves 2.4 45
flitch 4.0 30
brawn 2.5 56
welt 3.7 67
salami 3.0 95
sausage 5.9 98 >
==> map { KnapsackItem.new($^a, $^b, $^c) }
==> sort {*.ppw}
{
{ #For-Loop inside gather
my $last_onelast-one = .cut_maybecut-maybe($max_wmax-w);
take $_;
$max_wmax-w -= .weight;
last if $last_onelast-one;
}</lang>
{say ~$_}
</lang>
'''Output:'''
<pre>
Anonymous user