#! perl -slw use strict; use List::Util qw[ sum ]; use Data::Dump qw[ pp ]; $Data::Dump::WIDTH = 1000; my %chemsAndFlows; while( ) { my( $chem, $mach, $flow ) = split ' '; next if $flow == 0; push @{ $chemsAndFlows{ $chem } }, $flow; } @$_ = sort{ $a <=> $b } @$_ for values %chemsAndFlows; #pp \%chemsAndFlows; ## Greedy; our $MACHMAX //= 11000; my( $iMach, %machsAssigned ) = 0; while( keys %chemsAndFlows ) { my( $machTotal, $mach ) = ( 0, sprintf "E%03d", ++$iMach); for my $chem ( keys %chemsAndFlows ) { for my $iFlow ( reverse 0 .. $#{ $chemsAndFlows{ $chem } } ) { my $flow = $chemsAndFlows{ $chem }[ $iFlow ]; die "MACHMAX too small for $chem:$flow" unless $flow < $MACHMAX; if( ( $machTotal + $flow ) <= $MACHMAX ) { $machTotal += $flow; push @{ $machsAssigned{ $mach }{ $chem } }, $flow; splice @{ $chemsAndFlows{ $chem } }, $iFlow, 1; delete $chemsAndFlows{ $chem } unless @{ $chemsAndFlows{ $chem } }; } } } } $_->{ ' total' } = sum( map @$_, values %$_ )for values %machsAssigned; pp \%machsAssigned; #1st column is unique chemical identifier 2nd column is unique machine identifier 3rd column is processing seconds __DATA__