Ruby-如何获取数组元素的所有组合

时间:2019-05-26 13:33:20

标签: arrays ruby combinations

如果我有一个数组:

%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],如果我想全部我应该得到的三位数组合

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

1 个答案:

答案 0 :(得分:2)

您正在寻找permutation而不是WWW-Authenticate

在组合中,我们不在乎元素的顺序,而仅在意集合中所有元素的存在。

ntlm()