Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Puzzle: need a more general algorithm

by fglock (Vicar)
on Jul 08, 2002 at 20:42 UTC ( #180319=note: print w/ replies, xml ) Need Help??


in reply to Puzzle: need a more general algorithm

If you want to generate all possible combinations, you could use this algorithm:

$categories = 5; $columns = 3; $a = join('#', 0..$categories); @columns = (); &check_columns ($a, @columns); sub check_columns { my $cat = shift; my @columns = @_; my $size = split('#', $cat)-1; foreach (1.. $size ) { my ($first, $second) = $cat =~ /^((?:.*?#){$_})(.*?)$/; $first =~ s/#$//; my @result = ($first, $second, @columns); if ($#result == $columns) { print join(" ", @result), "\n", } else { check_columns(@result); } } }

It generates this list of indexes, from which you can choose the best line:

0 1 2 3#4#5 0 1 2#3 4#5 0 1#2 3 4#5 0#1 2 3 4#5 0 1 2#3#4 5 0 1#2 3#4 5 0#1 2 3#4 5 0 1#2#3 4 5 0#1 2#3 4 5 0#1#2 3 4 5

I used an array of strings instead of an array of arrays because it is easier to debug.


Comment on Re: Puzzle: need a more general algorithm
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://180319]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (6)
As of 2014-09-02 05:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite cookbook is:










    Results (20 votes), past polls