Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: Generate sequential array element combos

by kelan (Deacon)
on Jul 29, 2004 at 15:31 UTC ( [id://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?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (4)
As of 2024-04-19 23:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found