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

Re: How can one generate all possible combinations with reference to string positions?

by kennethk (Monsignor)
on Feb 20, 2013 at 22:20 UTC ( #1019852=note: print w/ replies, xml ) Need Help??


in reply to How can one generate all possible combinations with reference to string positions?

So, I decided to take a formal cut at the general problem. Given your problem statement, I thought the most reasonable specification would be a string of 'main groups' in order. Also, rather than reinventing the wheel, I used List::Permutor as recommended in perlfaq4's How do I permute N elements of a list?.

#!/usr/bin/perl -w use strict; use List::Permutor; my $groups = 'LHLH'; my %count; $count{$_}++ for split //, $groups; my @results = $groups; for my $key (keys %count) { my $perm = new List::Permutor 1 .. $count{$key}; my @indices; while (my @set = $perm->next) { push @indices, \@set; } for my $result (@results) { $result =~ s/(?<=$key)/%d/g; $result = [map sprintf($result, @$_), @indices]; } @results = map @$_, @results; } print join "\n", @results;
I've used sprintf for index templating. There's a potential problem with memory usage getting a bit large since it holds all variants in memory. The solution to that, I expect, would involve recursive functions. Of course, this kind of problem hits anytime you invoke factorial scaling.

#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.


Comment on Re: How can one generate all possible combinations with reference to string positions?
Download Code
Re^2: How can one generate all possible combinations with reference to string positions?
by frozenwithjoy (Curate) on Feb 21, 2013 at 00:46 UTC
    That's nice, fast, and relatively simple!

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (8)
As of 2014-10-21 08:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (98 votes), past polls