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.
