in reply to Computer science Problem - single dimension bin packing
What are you trying to optimize? Are you trying to get an even distribution of data across a fixed number of drives? Efficiently fill drives of fixed size? The latter is (as AppleFritter points out) the knapsack problem.
For case 1), a simple and quite effective solution is to go from largest object to smallest, putting it in the least filled bin.
output:#!/usr/bin/perl use warnings; use strict; use Data::Dumper; my %bins = ( A => 0, B => 0, C => 0, D => 0, ); my %dir; my $int; while(<DATA>) { chomp; my ($size, $name) = split /\s+/; $name .= ++$int if $dir{$name}; # Disabiguation; all your names ar +e identical $dir{$name} = $size; } for my $name (sort {$dir{$b} <=> $dir{$a}} keys %dir) { my ($smallest) = sort {$bins{$a} <=> $bins{$b}} keys %bins; $bins{$smallest} += $dir{$name}; } print Dumper(\%bins);
$VAR1 = { 'A' => '9885811019', 'D' => '9885704251', 'C' => '9885960464', 'B' => '9885704533' };
For case 2), you would put it in the smallest available space in which it fits.
outputs#!/usr/bin/perl use warnings; use strict; use Data::Dumper; my $max = 10**10; my $new_bin = 'A'; my %bins; my %dir; my $int; while(<DATA>) { chomp; my ($size, $name) = split /\s+/; $name .= ++$int if $dir{$name}; # Disabiguation; all your names ar +e identical $dir{$name} = $size; } DIR_LOOP: for my $name (sort {$dir{$b} <=> $dir{$a}} keys %dir) { for my $bin_name (sort {$bins{$b} <=> $bins{$a}} keys %bins) { if ($bins{$bin_name} + $dir{$name} < $max) { $bins{$bin_name} += $dir{$name}; next DIR_LOOP; } } $bins{$new_bin++} = $dir{$name}; } print Dumper(\%bins);
$VAR1 = { 'A' => '9999831421', 'D' => '9543689031', 'C' => '9999660101', 'B' => '9999999714' };
Update: Added code
#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Computer science Problem - single dimension bin packing
by ikegami (Patriarch) on Aug 14, 2014 at 17:08 UTC | |
by FloydATC (Deacon) on Aug 14, 2014 at 18:29 UTC | |
by ikegami (Patriarch) on Aug 14, 2014 at 19:18 UTC | |
by FloydATC (Deacon) on Aug 14, 2014 at 20:13 UTC | |
by kennethk (Abbot) on Aug 14, 2014 at 18:03 UTC | |
|
Re^2: Computer science Problem - single dimension bin packing
by davis (Vicar) on Aug 15, 2014 at 12:11 UTC | |
by kennethk (Abbot) on Aug 15, 2014 at 14:45 UTC |