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

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

Approaches:

1.Metaprogramming

Generate dynamically a string of the above code with all nesting and eval it. (fast and intuitive!)

2. Recursion

Write a function X2() which gets two arrayrefs and returns an arr_ref of the cross product. Call it recursively until @array exceeded.

3. Reduce

is a variation of the above, with List::Util::reduce

use Data::Dumper; #- crossproduct of two array refs sub X2 { my ($a,$b)=@_; my @result; for my $x (@$a) { for my $y (@$b) { unless (ref($x) eq "ARRAY"){ push @result, [$x,$y]; }else{ push @result, [(@$x,$y)]; } } } return \@result; } use List::Util qw/reduce/; #- crossproduct of list of array refs sub X { reduce { X2($a,$b) } @_ } my @array = ( [ "a", "b", "c", ], [ "1", "2", "3", "4", ], [ "x", "y", ], ); print Dumper X(@array);

The function X() now works somehow like the X operator in perl6, but of course you could also use reduce { X2($a,$b) } @array directly.

The function X2() could be rewritten with two nested maps, but thats a little two cryptic for my taste.

Bad ideas:

1. Glob

that's a hack which only works for strings as element type, everything else will be stringified, eg refs!!!

Cheers Rolf

UPDATES:

* just noticed that you only want a simple concatenation of strings. That simplifies the code...

* There is a problem with this code .. the first one to spot it gets upvoted! :)


In reply to Re: Generating all possible combinations from an AoA by LanX
in thread Generating all possible combinations from an AoA by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • 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.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (7)
As of 2024-04-23 06:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found