|Think about Loose Coupling|
Puzzle: need a more general algorithmby Ovid (Cardinal)
|on Jul 08, 2002 at 19:13 UTC||Need Help??|
Ovid has asked for the
wisdom of the Perl Monks concerning the following question:
I've wound up with a bit of a tricky and ugly code that I need to make more flexible. The problem: We have a client who displays their products on our Web site. These products are divided into several categories that are displayed in multiple columns. Here are the rules:
For example, let's say I have categories one through six with these respective heights (number of products):
With that, I might have those categories distributed as follows (pretending that the index starts with 1 instead of zero):
The following code will accurately determine that, noting that I need to sort the actual values in each column. Further, it takes into account that the 1st and 6th category will always be in columns 1 and 4, respectively. Each for loop is iterating over a subsequent category with the indices being the only allowable values for a category (the second category is $a and cannot possibly be in column 3 because that would leave column 2 empty).
That code results in 121 iterations. Some possibilities are skipped by last if ! $valid_dist because the for loops that I have written sometimes allow for invalid combinations (if the 5th category ($d) is in the fourth column, the 4th category cannot be in the second column because that would leave the third column empty).
My real problem: the client dictates changes to the Web site faster than a jackrabbit ... uh, never mind ... you get the idea.
Essentially, this used to be two columns. It's now four. It may turn into three columns. We may have another category added or removed. My code snippet works, but if the client changes his mind again, it would be nice to simply have the code work. Any suggestions?
Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.