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

前端 未结 5 1530
無奈伤痛
無奈伤痛 2021-01-01 22:52

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

5条回答
  •  一生所求
    2021-01-01 23:26

    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
    

提交回复
热议问题