Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
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 making s'mores by the fire in the courtyard of the Monastery: (6)
As of 2015-07-02 04:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (27 votes), past polls