I figure you'll always combine the smallest category with the one before or after it (
Update: realized that in general, this is not a valid assumption; finding example left as excercise, though maybe finding smallest consecutive two column sum, then generating possibilities summing of columns before and after that might work...), so here's my fairly (in)efficient (O(N**2)) answer:
#!/usr/bin/perl
use strict;
use warnings;
my $num_columns = 4;
my @cat = (15, 15, 10, 10, 15, 15);
my @ans = squish(@cat);
print "@ans\n";
sub squish {
my @arr = @_;
my @aoa = (\@arr);
for ($num_columns..(@arr-1)) {
my @tmp_aoa;
push @tmp_aoa, squisher(@$_) for @aoa;
@aoa = @tmp_aoa;
}
my $best_ans;
my $best_value;
for my $aref (@aoa) {
my $max_value;
for my $value (@$aref) {
$max_value = $value if !defined $max_value or $value > $max_valu
+e;
}
$best_ans = $aref, $best_value = $max_value
if !defined $best_value or $max_value < $best_value;
}
@$best_ans;
}
sub squisher {
my @arr = @_;
my $min_col;
my $min_value;
for (0..$#arr) {
$min_value = $arr[$_], $min_col = $_
if !defined $min_value or $arr[$_] < $min_value;
}
my @arr1 = ($min_col > 0) ? @arr : ();
my @arr2 = ($min_col < $#arr) ? @arr : ();
splice(@arr1, $min_col-1, 2, $arr1[$min_col-1] + $arr1[$min_col])
if @arr1;
splice(@arr2, $min_col, 2, $arr2[$min_col] + $arr2[$min_col+1])
if @arr2;
return ((@arr1 ? \@arr1 : ()), (@arr2 ? \@arr2 : ()));
}
Update: mildly tested...
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.