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

前端 未结 5 1525
無奈伤痛
無奈伤痛 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:34

    That's actually not permutation but Cartesian product. See Math::Cartesian::Product.

    #!/usr/bin/perl
    
    use strict; use warnings;
    
    use Math::Cartesian::Product;
    
    cartesian { print "@_\n" }
        ["big", "tiny", "small"],
        ["red", "yellow", "green"],
        ["apple", "pear", "banana"];
    

    Output:

    C:\Temp> uu
    big red apple
    big red pear
    big red banana
    big yellow apple
    big yellow pear
    big yellow banana
    big green apple
    big green pear
    big green banana
    tiny red apple
    tiny red pear
    tiny red banana
    tiny yellow apple
    tiny yellow pear
    tiny yellow banana
    tiny green apple
    tiny green pear
    tiny green banana
    small red apple
    small red pear
    small red banana
    small yellow apple
    small yellow pear
    small yellow banana
    small green apple
    small green pear
    small green banana

提交回复
热议问题