Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Perl, how can I get the Cartesian product of multiple sets?

I want to do permutation in Perl. For example I have three arrays: ["big", "tiny", "small"] and then I have ["red", "yellow", "green"] and also ["apple", "pear", "banana"].

How do I get:

["big", "red", "apple"]
["big", "red", "pear"]

..etc..

["small", "green", "banana"]

I understand this is called permutation. But I am not sure how to do it. Also I don't know how many arrays I can have. There may be three or four, so I don't want to do nested loop.

like image 830
user295033 Avatar asked Mar 16 '10 18:03

user295033


1 Answers

IF

  • you don't want to include dependencies
  • you have a small number of arrays
  • your arrays are not really huge

then you can simply do this:

For two arrays @xs and @ys:

map{ my $x = $_; map { [$x, $_] } @ys } @xs

For three arrays @xs, @ys, @zs

map{ my $x = $_; map { my $y = $_; map { [$x, $y, $_] } @zs } @ys } @xs
like image 175
Dacav Avatar answered Oct 22 '22 00:10

Dacav