在Perl中,如何获得多个集合的笛卡尔积? [英] In Perl, how can I get the Cartesian product of multiple sets?

查看:135
本文介绍了在Perl中,如何获得多个集合的笛卡尔积?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Perl中进行置换.例如,我有三个数组:["big", "tiny", "small"],然后有["red", "yellow", "green"]["apple", "pear", "banana"].

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"].

我如何获得:

["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.

推荐答案

实际上不是排列,而是笛卡尔积.参见 Math :: Cartesian :: Product .

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"];

输出:

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

这篇关于在Perl中,如何获得多个集合的笛卡尔积?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆