perl-哈希的所有可能组合 [英] perl - all possible combinations of hash
本文介绍了perl-哈希的所有可能组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
告诉我如何获取哈希的所有可能组合
tell me how to get every possible combination of hash
以下是示例
my %data = (
'a' => [qw(a1 a2 a3)],
'b' => [qw(b1 b2 b3)],
'c' => [qw(c1 c2 c3)]);
获得
a1
a2
a3
b1
b2
b3
c1
c2
c3
a1 b1
a1 b2
a1 b3
a1 c1
a1 c2
a1 c3
b1 c1
b1 c2
b1 c3
b2 c1
b2 c2
b2 c3
b3 c1
b3 c2
b3 c3
a1 b1 c1
a1 b1 c2
a1 b1 c3
a1 b2 c1
a1 b2 c2
a1 b2 c3
a1 b3 c1
a1 b3 c2
a1 b3 c3
a2 b1 c1
a2 b1 c2
a2 b1 c3
a2 b2 c1
a2 b2 c2
a2 b2 c3
a2 b3 c1
a2 b3 c2
a2 b3 c3
a3 b1 c1
a3 b1 c2
a3 b1 c3
a3 b2 c1
a3 b2 c2
a3 b2 c3
a3 b3 c1
a3 b3 c2
a3 b3 c3
谢谢
推荐答案
我的模块列表: :Gen 包含一个cartesian
函数,可以产生所需的结果.这段代码似乎可以解决问题,但是您的示例并未包含将产生的所有排列,我认为这只是该示例中的一个省略.
My module List::Gen contains a cartesian
function that can produce the results you want. This code seems to do the trick, but your example does not contain all of the permutations that this will produce, which I am assuming is just an omission in the example.
use List::Gen 'cartesian';
my %data = (
'a' => [qw(a1 a2 a3)],
'b' => [qw(b1 b2 b3)],
'c' => [qw(c1 c2 c3)],
);
my $product = cartesian {join ' ' => sort grep defined, @_}
map {[@$_, undef]}
values %data;
say for sort {length $a <=> length $b or $a cmp $b} @$product;
有点密集,所以要解释一下:
That is a bit dense, so to explain:
-
values %data
返回%data
中的数组
-
map {[@$_, undef]}
然后在每个值的末尾附加一个空值,因为您需要部分组合 -
cartesian {join ' ' => sort grep defined, @_}
然后完成工作,计算数组的笛卡尔积,同时减去未定义的元素,并对值进行排序,如您的示例所示. -
sort {length $a <=> length $b or $a cmp $b} @$product
然后按照指定的顺序打印出产品.
values %data
returns the arrays in%data
map {[@$_, undef]}
then attaches an empty value to the end of each, since you want the partial combinationscartesian {join ' ' => sort grep defined, @_}
then does the meat of the work, computing the Cartesian product of the arrays while subtracting out the undefined elements, and sorting the values as your example shows.sort {length $a <=> length $b or $a cmp $b} @$product
then prints out the product in the order specified.
这篇关于perl-哈希的所有可能组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文