Knapsack problem/Continuous: Difference between revisions

No edit summary
Line 641:
;;</lang>
 
=={{header|Perl 6}}==
This Solutions sorts the item by WEIGHT/VALUE
<lang perl6>
class KnapsackItem{
has ($.name, $.weight is rw,$.price is rw, $.ppw);
method new (Str $n, $w, $p){
KnapsackItem.bless(*, :name($n), :weight($w), :price($p), :ppw($w/$p))
}
 
method cut_maybe ($_: $max_weight){
return False if $max_weight > .weight;
.price = (1/.ppw) * $max_weight;
.weight = .ppw * .price;
return True;
}
 
method Str ($_:){sprintf "%8s %1.2f %3.2f",.name, .weight, .price}
};
 
my ($max_w, @in_knapsack) = 15;
 
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}
{
my $last_one = .cut_maybe($max_w);
push @in_knapsack, $_;
$max_w -= .weight;
last if $last_one;
}
 
#Output:
say "Item Portion Value";
for @in_knapsack {say .Str}
printf "TOTAL: %1.2f %1.2f\n",([+]@in_knapsack».weight),[+]@in_knapsack».price
</lang>
'''Output:'''
<pre>
perl6 knapsack_continous.p6
Item Portion Value
salami 3.00 95.00
ham 3.60 90.00
brawn 2.50 56.00
greaves 2.40 45.00
welt 3.50 63.38
TOTAL: 15.00 349.38
</pre>
=={{header|PicoLisp}}==
<lang PicoLisp>(scl 2)
38

edits