本文介绍了阵列的所有组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有数组

  A = [W1,W2,W3]
 

我怎样才能生成一个新的数组值的每个组合?我需要的输出是这样的:

  [W1,W2,W3,W1 W1,W1 W2,W1 W3,W2 W1,W2 W2, W2 W3,W3 W1,W3 W2,W3 W3,W1 W1 W1,W1 W1 W2,W1 W1 W3,W1 W2 W1,W1 W2 W2, W1 W2 W3,W2 W1 W1,W2 W1 W2,W2 W1 W2,W2 W1 W3,W2 W2 W1,W2 W2 W2,W2 W2 W3,W2 W3 W1,W2 W3 W2,W2 W3 W3,W3 W1 W1,W3 W1 W2,W3 W1 W3,W3 W2 W1,W3 W2 W2,W3 W2 W3 ,W3 W3 W1,W3 W3 W2,W3 W3 W2]
 

从尝试code href="http://stackoverflow.com/questions/10900636/generate-array-of-all-combinations-of-an-existing-array">Generate现有阵列的所有组合的阵列

结果不正确

 W1,W2,W3,W1 W2,W1 W3,W2 W3,W1 W2 W3]
 

解决方案

下面是做到这一点的一种方式,但这样的结果有W3 W3 W3和你想要的结果没有,但我看不出逻辑,包括W3 W3和W1 W1 W1,而不是W3 W3 W3,所以我以为你只是错过补充说。

您正在寻找的是不是组合,但排列(与repetation):

  A = [W1,W2,W3]

结果=(1..a.size).flat_map办|大小|
  a.repeated_permutation(尺寸).MAP {|烫发| perm.join('')}
结束
 

I have array

a = ["w1", "w2", "w3"]

How can I generate a new array with every combination of values?I need the output to look like this:

["w1", "w2", "w3", "w1 w1", "w1 w2", "w1 w3", "w2 w1", "w2 w2", "w2 w3", "w3 w1", "w3 w2", "w3 w3", "w1 w1 w1", "w1 w1 w2", "w1 w1 w3", "w1 w2 w1", "w1 w2 w2", "w1 w2 w3", "w2 w1 w1", "w2 w1 w2", "w2 w1 w2", "w2 w1 w3", "w2 w2 w1", "w2 w2 w2", "w2 w2 w3", "w2 w3 w1", "w2 w3 w2", "w2 w3 w3", "w3 w1 w1", "w3 w1 w2", "w3 w1 w3", "w3 w2 w1", "w3 w2 w2", "w3 w2 w3", "w3 w3 w1", "w3 w3 w2", "w3 w3 w2"]

Try code from Generate array of all combinations of an existing array

Result incorrect

"w1", "w2", "w3", "w1 w2", "w1 w3", "w2 w3", "w1 w2 w3"]
解决方案

Here is one way to do it, however this result has "w3 w3 w3" and you desired result does not, but I do not see the logic to include "w3 w3" and "w1 w1 w1" but not "w3 w3 w3", so I assume you just missed to add that.

What you are looking for is not the combinations, but the permutations (with repetation):

a = ["w1", "w2", "w3"]

result = (1..a.size).flat_map do |size|
  a.repeated_permutation(size).map { |perm| perm.join(' ') }
end

这篇关于阵列的所有组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 09:49