Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

Re: Re: Puzzle: need a more general algorithm

by Ovid (Cardinal)
on Jul 09, 2002 at 02:56 UTC ( #180388=note: print w/replies, xml ) Need Help??

in reply to Re: Puzzle: need a more general algorithm
in thread Puzzle: need a more general algorithm

It appears that I have confused a few people here. What I need "minimized" is the aggregate height per column as summed from @height data.

Given the heights of qw/ 10 10 15 20 10 10 /, I could conceivably construct a table with no column having greater than 20 items in it:

10 15 20 10 10 10

The following solution, would fail because one of the columns has 25 items:

10 10 20 10 15 10

Part of the problem, I suspect, is that I had a bug in my original code because I accidentally posted the wrong version. The @distribution array needs to be reset every iteration. The following is correct:

#!/usr/bin/perl -w use strict; use Data::Dumper; my @height = qw/ 10 15 25 30 10 13 /; my @columns = ($height[0],0,0,$height[-1]); my $curr_height = 0; # set this unreasonably high to ensure that subsequent # heights will be lower $curr_height += $_ foreach @height; my @distribution; for my $a (0..1) { $columns[$a] += $height[1]; for my $b (0..2) { $columns[$b] += $height[2]; for my $c (1..3) { $columns[$c] += $height[3]; for my $d (2..3) { $columns[$d] += $height[4]; my $this_height = ( sort @columns )[-1]; my $valid_dist; foreach ( @columns ) { $valid_dist = $_; last if ! $valid_dist; } if ( $valid_dist and $this_height < $curr_height ) { $curr_height = $this_height; @distribution = ([1],[],[],[6]); push @{$distribution[$a]}, 2; push @{$distribution[$b]}, 3; push @{$distribution[$c]}, 4; push @{$distribution[$d]}, 5; } $columns[$d] -= $height[4]; } $columns[$c] -= $height[3]; } $columns[$b] -= $height[2]; } $columns[$a] -= $height[1]; } print Dumper \@distribution;

I hope that's clear, now :)

I also have to add that there's a heck of a lot more discussion on this than I thought there would be.


Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://180388]
[hippo]: yum update perl
[hippo]: Other package managers are available
LanX wouldn't update system Perl!
[Discipulus]: prathap keerthipati might be it is better to install an alternative Perl instead and do not touch the system one
[LanX]: see perlbrew for alternative Perl installations
[marto]: unless you know exactly what you're doing an often saner option is to simply build another Perl rather than replace the system one

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (14)
As of 2017-03-23 10:40 GMT
Find Nodes?
    Voting Booth?
    Should Pluto Get Its Planethood Back?

    Results (285 votes). Check out past polls.