Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate all possibles combinations of an array with a length within a given range

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?

like image 583
fschuindt Avatar asked Jan 21 '13 02:01

fschuindt


People also ask

How do you get all possible number combinations?

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.

How do you print all array combinations?

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

How do you generate all possible combinations of a set of numbers in Java?

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);


1 Answers

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).

like image 169
dbenhur Avatar answered Nov 05 '22 00:11

dbenhur