こんなのはどうでしょう。
%taikyuu = (
'A' => 10,
'B' => 20,
'C' => 15,
'D' => 12,
'E' => 8);
%fuka = (
'A' => 100,
'B' => 80,
'C' => 60,
'D' => 60,
'E' => 88);
@hashkeys = keys %taikyuu;
@hashkeys = sort @hashkeys;
#重さが10,11,12の荷物が来たとき
foreach $_(10,11,12){
undef $minikey;
undef $minifutan;
foreach $hashkey(@hashkeys){
$futan = $fuka{$hashkey} + $fuka{$hashkey} * $_;
if(!$minifutan or $futan < $minifutan){
$minifutan = $futan;
$minikey = $hashkey;
}
}
$fuka{$minikey} += $taikyuu{$minikey} * $_;
}
自分の勉強がてら書いてみた。
#!/usr/bin/env perl package Container; use Moose; has _initial_load => (is => 'ro', isa => 'Int', required => 1); has _persistence => (is => 'ro', isa => 'Int', required => 1); has name => (is => 'ro', isa => 'Str', required => 1); has weight => (default => 0, is => 'rw', isa => 'Int', writer => '_weight'); around BUILDARGS => sub { my $orig = shift; my $class = shift; if (@_ == 3) { my ($name, $initial_load, $persistence) = @_; return $class->$orig(_initial_load => $initial_load, _persistence => $persistence, name => $name); } else { return $class->$orig(@_); } }; sub add_weight { my $self = shift; my $weight = shift or die; $self->_weight($self->weight + $weight); return $self; } sub clone { my $self = shift; return Container->new(_initial_load => $self->_initial_load, _persistence => $self->_persistence, name => $self->name, weight => $self->weight); } sub load { my $self = shift; return $self->_initial_load + $self->weight * $self->_persistence; } package main; use Modern::Perl; my $container = [Container->new('A', 10, 100), Container->new('B', 20, 80), Container->new('C', 15, 60), Container->new('D', 12, 60), Container->new('E', 8, 88)]; foreach my $weight (10, 11, 12) { (sort {$a->clone->add_weight($weight)->load <=> $b->clone->add_weight($weight)->load} @$container)[0]->add_weight($weight); }