perl - 哈希的所有可能组合
告诉我如何获取哈希的每种可能组合
这是一个示例
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
谢谢
tell me how to get every possible combination of hash
Here is an example
my %data = (
'a' => [qw(a1 a2 a3)],
'b' => [qw(b1 b2 b3)],
'c' => [qw(c1 c2 c3)]);
to get
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
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 brian d foy 的
Set::CrossProduct
模块。您需要以明显的方式将哈希值整理为数组数组。Use brian d foy's
Set::CrossProduct
module. You'll need to massage your hash into array of arrays in an obvious way.我的模块 List::Gen 包含一个
cartesian
函数可以产生你想要的结果。这段代码似乎可以解决问题,但您的示例并不包含这将产生的所有排列,我假设这只是示例中的一个遗漏。这有点密集,所以解释一下:
values %data
返回%data
中的数组map {[@$_, undef]}
然后在每个末尾附加一个空值,因为您需要部分组合cartesian {join ' ' =>; sort grep Defined,@_}
然后完成主要工作,计算数组的笛卡尔积,同时减去未定义的元素,并对值进行排序,如示例所示。sort {长度$a <=>; length $b 或 $a cmp $b} @$product
然后按指定的顺序打印出产品。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.That is a bit dense, so to explain:
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.