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.


In reply to Re^3: I want to maximize data storage in a DVD by ikegami
in thread I want to maximize data storage in a DVD by mgrangeiro

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.