fsc*_*ndt 24 ruby arrays combinations
如何生成长度在给定范围内的数组元素的所有可能组合?例如:
('a'..'f').to_a.all_possibilities(3, 5)
Run Code Online (Sandbox Code Playgroud)
应该产生如下数组:
['abc', 'abd', 'abe', 'abf', ..., 'abcde', 'abcdf', 'abcda', ...]
Run Code Online (Sandbox Code Playgroud)
包括从"abc"(三个字符)到('a'..'f').to_a五个字符长度的最后一个可能组合.我不知道该怎么做.有帮助吗?
dbe*_*hur 52
Array#combination 是stdlib:
[1] pry(main)> a = ('a'..'f').to_a
=> ["a", "b", "c", "d", "e", "f"]
[2] pry(main)> a.combination(3).to_a
=> [["a", "b", "c"],
["a", "b", "d"],
["a", "b", "e"],
["a", "b", "f"],
["a", "c", "d"],
["a", "c", "e"],
["a", "c", "f"],
["a", "d", "e"],
["a", "d", "f"],
["a", "e", "f"],
["b", "c", "d"],
["b", "c", "e"],
["b", "c", "f"],
["b", "d", "e"],
["b", "d", "f"],
["b", "e", "f"],
["c", "d", "e"],
["c", "d", "f"],
["c", "e", "f"],
["d", "e", "f"]]
Run Code Online (Sandbox Code Playgroud)
如果你想要所有尺寸min到max的组合:
(min..max).flat_map{|size| a.combination(size).to_a }
Run Code Online (Sandbox Code Playgroud)
如果您希望将它们转换为字符串,只需替换.to_a为.map(&:join).
saw*_*awa 13
(3..5).flat_map{|n| ('a'..'f').to_a.combination(n).map(&:join)}
Run Code Online (Sandbox Code Playgroud)
编辑:满足OP的明确意图,使用repeated_permutation.
(3..5).flat_map{|n| ('a'..'f').to_a.repeated_permutation(n).map(&:join)}
Run Code Online (Sandbox Code Playgroud)