本文介绍了生成所有候选条件的给定范围内的一个长度的阵列的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何可以生成一个给定的范围内,长度的数组元素的所有可能的组合?例如:
How can I generate all possible combinations of elements of an array with a length within a given range? E.g.:
('a'..'f').to_a.all_possibilities(3, 5)
应该产生一个数组,如:
should produce an array like:
['abc', 'abd', 'abe', 'abf', ..., 'abcde', 'abcdf', 'abcda', ...]
包括ABC
(三个字符)到('A'..'F')。to_a的最后一个可能的组合
与五个字符长度。我不知道如何做到这一点。任何帮助吗?
including from "abc"
(three characters) up to the last possible combination of ('a'..'f').to_a
with five characters length. I have no idea how to do this. Any help?
推荐答案
<$c$c>Array#combination$c$c>是STDLIB:
Array#combination
is 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"]]
如果你想要的大小分所有组合到最大:
if you want all combinations of size min to max:
(min..max).flat_map{|size| a.combination(size).to_a }
如果您希望它们转换为字符串,只需更换 .to_a
与 .MAP(安培;:加入)
If you want them converted to strings, just replace .to_a
with .map(&:join)
.
这篇关于生成所有候选条件的给定范围内的一个长度的阵列的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!