Created
January 27, 2011 07:36
-
-
Save sorear/798202 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!./perl6 | |
# this is close to the Dynamic programming solution from Wikipedia, | |
my class knapsackItem{has $.name; has $.weight;has $.unit;} | |
sub func (@a, $w, $v = 0){ | |
return $v if $w == 0 || !@a; | |
my @rest = @a; | |
my $i = shift @rest; | |
my @skip = func(@rest,$w,$v); | |
if $w >= $i.weight { # next one fits | |
my @put = func( @rest,$w - $i.weight,$v + $i.unit); | |
return (@put, $i.name) if @put[0] > @skip[0]; | |
} | |
return @skip; | |
}; | |
my $MAX_WEIGHT = 400; | |
my @table; | |
push @table, knapsackItem.new: name => 'map' , weight => 9 , unit => 150; | |
push @table, knapsackItem.new: name => 'compass' , weight => 13 , unit => 35; | |
push @table, knapsackItem.new: name => 'water' , weight => 153 , unit => 200; | |
push @table, knapsackItem.new: name => 'sandwich' , weight => 50 , unit => 160; | |
push @table, knapsackItem.new: name => 'glucose' , weight => 15 , unit => 60; | |
push @table, knapsackItem.new: name => 'tin' , weight => 68 , unit => 45; | |
push @table, knapsackItem.new: name => 'banana' , weight => 27 , unit => 60; | |
push @table, knapsackItem.new: name => 'apple' , weight => 39 , unit => 40; | |
push @table, knapsackItem.new: name => 'cheese' , weight => 23 , unit => 30; | |
push @table, knapsackItem.new: name => 'beer' , weight => 52 , unit => 10; | |
push @table, knapsackItem.new: name => 'suntan cream' , weight => 11 , unit => 70; | |
push @table, knapsackItem.new: name => 'camera' , weight => 32 , unit => 30; | |
push @table, knapsackItem.new: name => 'T-shirt' , weight => 24 , unit => 15; | |
push @table, knapsackItem.new: name => 'trousers' , weight => 48 , unit => 10; | |
push @table, knapsackItem.new: name => 'umbrella' , weight => 73 , unit => 40; | |
push @table, knapsackItem.new: name => 'waterproof trousers' , weight => 42 , unit => 70; | |
push @table, knapsackItem.new: name => 'waterproof overclothes' , weight => 43 , unit => 75; | |
push @table, knapsackItem.new: name => 'note-case' , weight => 22 , unit => 80; | |
push @table, knapsackItem.new: name => 'sunglasses' , weight => 7 , unit => 20; | |
push @table, knapsackItem.new: name => 'towel' , weight => 18 , unit => 12; | |
push @table, knapsackItem.new: name => 'socks' , weight => 4 , unit => 50; | |
push @table, knapsackItem.new: name => 'book' , weight => 30 , unit => 10; | |
my ($value, @result) = func(@table,$MAX_WEIGHT); | |
say "Value = $value\nTourist put in the bag:\n{join " ", @result}"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment