Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Generate sequential array element combos

by kelan (Deacon)
on Jul 29, 2004 at 15:31 UTC ( #378402=note: print w/replies, xml ) Need Help??


in reply to Generate sequential array element combos

Here's a clever, yet impractical, solution. It combines the eye-popping memory growth of tye's first solution, with the incomprensibility of string building.

Anyway, glob() can do this pretty handily, the problem is you need to build the string it uses first:

use strict; use warnings; # setup bounds my @digits = ( 0 .. 9 ); my $min_digits = 4; my $max_digits = 6; # build the glob string my $glob_string; for my $dignum ( 1 .. $max_digits ) { if ( $dignum <= $max_digits - $min_digits ) { $glob_string .= '{' . join( ',', ( '', @digits ) ) . '}'; } else { $glob_string .= '{' . join( ',', @digits ) . '}'; } } # print the permutations my $num; while ( $num = glob( $glob_string ) ) { print $num, "\n"; }
$glob_string ends up looking like (split into two lines for better wrapping):
{,0,1,2,3,4,5,6,7,8,9}{,0,1,2,3,4,5,6,7,8,9}{0,1,2,3,4,5,6,7,8,9}
{0,1,2,3,4,5,6,7,8,9}{0,1,2,3,4,5,6,7,8,9}{0,1,2,3,4,5,6,7,8,9}
which glob uses to do the work.

I'll note that I was surprised by the memory consumption because in scalar context, glob is a simple iterator. But I suppose it builds all the matches up first and then iterates through them, instead of building them as it goes.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (3)
As of 2022-09-30 03:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I prefer my indexes to start at:




    Results (125 votes). Check out past polls.

    Notices?