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', ...]
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?
In fact, if you know the number of combinations, you can easily calculate the number of permutations: P(n,r) = C(n,r) * r! . If you switch on the advanced mode of this combination calculator, you will be able to find the number of permutations.
Method 1 (Fix Elements and Recur)We first fix 1 at index 0 in data[], then recur for remaining indexes, then we fix 2 at index 0 and recur. Finally, we fix 3 and recur for remaining indexes. When number of elements in data[] becomes equal to r (size of a combination), we print data[].
The combinations method returns all subsets of a given size. Next, let's use the combinations method to generate combinations: Set<Set<Integer>> combinations = Sets. combinations(ImmutableSet. of(0, 1, 2, 3, 4, 5), 3);
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 }
If you want them converted to strings, just replace .to_a
with .map(&:join)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With