Takes a list or array of array references and returns a function that will return successive permutations of the referenced arrays. Avoids recursion so will work on abitrarily huge sets of data. Runtime scales linearly with the number of sets. Minimal memory usage.
my @aoa = (
[('a'..'z')],
[('A'..'Z')],
[(1..26)],
);
my $iter = make_permutator(@aoa);
while (my @els = $iter->() ){
print @els,"\n";
}
sub make_permutator{
my @arefs = @_;
my @arrayindexes = ();
foreach (@arefs){
push @arrayindexes,[$_,0,$#{$_}];
}
return sub {
return if $arrayindexes[0]->[1] > $arrayindexes[0]->[2];
my @els = map { $_->[0]->[ $_->[1]] } @arrayindexes;
# Check for out of bounds....
$arrayindexes[$#arrayindexes]->[1]++;
for (my $i = $#arrayindexes; $i > 0; $i--){
if ($arrayindexes[$i]->[1] > $arrayindexes[$i]->[2
+]){
$arrayindexes[$i]->[1] = 0;
$arrayindexes[$i-1]->[1]++;
}else{
last;
}
}
return @els;
};
}
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|