Anonymous user
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 $.price is rw;
KnapsackItem.bless(*, :name($n), :weight($w), :price($p), :ppw($w/$p))▼
has $.ppw;
}▼
▲ 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}▼
$.price = $max-weight / $.ppw;
▲ return True;
}
my $max_w = 15;▼
$.name,
$.weight,
$.price }
say "Item Portion Value";
.say for gather
for < beef
pork
ham
greaves
flitch
brawn
welt
salami
sausage
==> map { KnapsackItem.new($^a, $^b, $^c) }
==> sort
{
my $
take $_;
$
last if $
}</lang>
'''Output:'''
<pre>
|