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...
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.