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

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


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


(3..5).flat_map{|n| ('a'..'f').to_a.combination(n).map(&:join)}

Edit: to meet OP's clarified intention, use repeated_permutation.

(3..5).flat_map{|n| ('a'..'f').to_a.repeated_permutation(n).map(&:join)}


You could modify my response to your previous question this way to get what you want.

class Array  def all_possibilities(from, to)    (from..to).flat_map do |i|      if i < size        permutation(i).to_a       else        permutation(to - i).flat_map do |e|          (self + e).permutation.to_a        end      end    end.map(&:join)  endendarray = ["F", "E", "R", "N", "A", "D", "O"]array.all_possibilities(3, 8)