如何在Ruby中获取数组元素的所有组合?

mw3dktmi  于 2023-06-05  发布在  Ruby
关注(0)|答案(2)|浏览(143)

如果我有一个数组:

%w(a b c d e)
=> ["a","b","c","d","e"]

我可以得到一些组合

irb(main):071:0> %w(a b c d e).combination(3).to_a
=> [["a", "b", "c"], ["a", "b", "d"], ["a", "b", "e"], ["a", "c", "d"], ["a", "c", "e"], ["a", "d", "e"], ["b", "c", "d"], ["b", "c", "e"], ["b", "d", "e"], ["c", "d", "e"]]

然而,这不是所有的组合,只是唯一的组合,例如。["e", "a", "b"]缺失
当我同样尝试使用较小的数组时,我只得到一个结果:

irb(main):059:0> %w(a b c).combination(3).to_a  
=> [["a", "b", "c"]]

我怎么能得到所有6个组合,即.对于['a', 'b', 'c'],我想得到

[['a','b','c'], ['a','c','b'], ['b', 'a', 'c'], ['b', 'c', 'a'], ['c', 'a', 'b'], ['c', 'b', 'a']

类似地,对于[1,2,3,4],如果我想要所有我应该得到的3位数组合

irb(main):074:0> [[1,2,3],[1,2,4],[1,3,2],[1,3,4],[1,4,2],[1,4,3],  [2,1,3],[2,1,4],[2,3,4],[2,3,1],[2,4,1],[2,4,2],  [3,1,2],[3,1,4],[3,2,3],[3,2,4],[3,4,2],[3,4,1]]

ttcibm8c

ttcibm8c1#

您正在查找permutation而不是combination
在组合中,我们不关心元素的顺序,只关心集合中所有元素的存在。

[1,2,3,4].permutation(3).to_a
#=> [[1, 2, 3], [1, 2, 4], [1, 3, 2], [1, 3, 4], [1, 4, 2], [1, 4, 3], [2, 1, 3], [2, 1, 4], [2, 3, 1], [2, 3, 4], [2, 4, 1], [2, 4, 3], [3, 1, 2], [3, 1, 4], [3, 2, 1], [3, 2, 4], [3, 4, 1], [3, 4, 2], [4, 1, 2], [4, 1, 3], [4, 2, 1], [4, 2, 3], [4, 3, 1], [4, 3, 2]]
lsmd5eda

lsmd5eda2#

Input: str = "AAB"
Output: 8
Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA".

验证码:-

arr= str.chars
new_arr = []

for index in 1..arr.length do
  new_arr<< arr.permutation(index).to_a.uniq
end

puts new_arr.flatten(1).count

相关问题