in reply to Re^2: I want to maximize data storage in a DVD
in thread I want to maximize data storage in a DVD

There's an example at the bottom of Algorithm::Knapsack. For weights, you'd use the size of the files and for the capacity, you'd use the capacity of a DVD.

Solution:

[ almust says this doesn't work. See Re^3: I want to maximize data storage in a DVD ]

use strict; use warnings; use Algorithm::Knapsack qw( ); use constant DVD_CAPACITY => ...; # Replace this function sub process_dvd { my ($dvd) = @_; use Data::Dumper qw( Dumper ); local $Data::Dumper::Useqq = 1; local $Data::Dumper::Terse = 1; local $Data::Dumper::Indent = 1; print(Dumper($dvd)); } sub fill_bag { my ($bag_size, $items) = @_; my @weights; for my $size (keys(%$items)) { push @weights, ($size) x @{$items->{$size}}; } return undef if !@weights; my $knapsack = Algorithm::Knapsack->new( capacity => $bag_size, weights => \@weights, ); $knapsack->compute(); my $solution = ( $knapsack->solutions() )[0] or die("No solution\n"); my @bag; for my $size (@$solution) { my $item = shift( @{$items->{$size}} ); push @bag, $item; } return \@bag; } { my %files; for my $file (...) { my $size = -s $file; push @{ $files{$size} }, $file; } while (my $dvd = fill_bag(DVD_CAPACITY, \%files)) { process_dvd($dvd); } }

Untested.

Update: Added solution.
Update: Fixed solution.

Replies are listed 'Best First'.
Re^4: I want to maximize data storage in a DVD
by mgrangeiro (Novice) on Mar 30, 2010 at 20:15 UTC
    Very helpful algorithm, ikegami. Thank you
Re^4: I want to maximize data storage in a DVD
by mgrangeiro (Novice) on Mar 31, 2010 at 15:19 UTC
    Is there a way to identify/read the size of the DVD so knapsack or bin-pack algorithm knows what to work with? Basically, I don't wanna use dvd_capacity as a constant since there are single and dual layer DVDs and other different media.
      It would be easier to have two constants and control which is used by a command line argument. If you disagree, don't hide your new question deep inside an "old" unrelated thread.