Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Puzzle: need a more general algorithm

by runrig (Abbot)
on Jul 09, 2002 at 01:42 UTC ( #180373=note: print w/replies, xml ) Need Help??


in reply to Puzzle: need a more general algorithm

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...

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://180373]
help
Chatterbox?
[Discipulus]: New Zeland and Italy share a simila faith!

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (4)
As of 2016-12-05 11:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    On a regular basis, I'm most likely to spy upon:













    Results (80 votes). Check out past polls.