Knapsack problem/Continuous: Difference between revisions

m
→‎{{header|Perl 6}}: fixed 'new' method
mNo edit summary
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}}
<lang perl>my @items = sort { $b->[2]/$b->[1] <=> $a->[2]/$a->[1] }
This Solutions sorts the item by WEIGHT/VALUE
(
<lang perl6>class KnapsackItem {
[qw'beef 3.8 36'],
has $.name;
[qw'pork 5.4 43'],
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) {
my ($limit, $value) = (15, 0);
self.bless(:name($n), :weight($w), :price($p), :ppw($w/$p))
}
 
method cut-maybe ($max-weight) {
print "item fraction weight value\n";
return False if $max-weight > $.weight;
for (@items) {
my $ratio.price = $_max->[1]weight >/ $limit ? $limit/$_->[1] : 1.ppw;
$.weight = $.ppw * print "$_->[0]\t".price;
return True;
$value += $_->[2] * $ratio;
}
$limit -= $_->[1];
 
if ($ratio == 1) {
method gist () { sprintf "%8s %1.2f %3.2f",
print " all\t$_->[1]\t$_->[2]\n";
} else { $.name,
printf "%5.3f %s %8.3f\n", $ratio, $_->[1] * $ratio, $_->[2] * $ratio;.weight,
last; $.price }
}
}
 
my $max-w = 15;
print "-" x 40, "\ntotal value: $value\n";
say "Item Portion Value";
</lang>
 
Output:<pre>item fraction weight value
.say for gather
salami all 3.0 95
ham for < beef all 3.68 9036
brawn all 2.5 pork 56 5.4 43
greaves all 2.4 ham 3.6 4590
welt 0.946 3.5 greaves 2.4 63.37845
[qw' flitch 4.0 30'],
----------------------------------------
[qw'ham brawn 32.65 90'],56
total value: 349.378378378378
[qw'beef welt 3.87 36'],67
[qw'welt salami 3.70 67'],95
[qw' sausage 5.9 98'], >
==> map({ KnapsackItem.new($^a, $^b, $^c) })
==> sort *.ppw
{
my $last-one = .cut-maybe($max-w);
}take $_;
$limitmax-w -= $_->[1].weight;
last if $last-one;
}</lang>
'''Output:'''
<pre>
%perl6 knapsack_continous.p6
Item Portion Value
[qw'salami 3.000 95'],.00
ham 3.60 90.00
[qw'brawn 2.550 56'],.00
[qw' greaves 2.440 45'],.00
welt 3.50 63.38
</pre>
 
2,392

edits