0

I want something like ["a", "b", "c"].all_possibilities(4) to produce: abc acb bac bca cab cba abca abcb abcc acba acbb acbc ... up to the last possible combination permutation using at most 4 characters from abc.

I tried permutations, but I don't think that's the case: %w[a b c].permutation.map &:join just permute, so length is no greater than three. Any help?

1
  • A naive implementation has N nested loops where N is your maximum length. Jan 17, 2013 at 9:02

1 Answer 1

1

What about ?

class Array
  def all_possibilities(range)
    return permutation(range).to_a if range < size

    (size..range).flat_map do |i|
      permutation(range - i).flat_map do |e|
        (self + e).permutation.to_a
      end
    end
  end
end

This returns an array of arrays of strings.

%w(a c).all_possibilities(3)
# => [["a", "c", "a"], ["a", "a", "c"], ["c", "a", "a"],
#     ["c", "a", "a"], ["a", "a", "c"], ["a", "c", "a"],
#     ["a", "c", "c"], ["a", "c", "c"], ["c", "a", "c"],
#     ["c", "c", "a"], ["c", "a", "c"], ["c", "c", "a"],
#     ["a", "c"], ["c", "a"]] 

To print it, you could just do result.map(&:join).join(', ').

ps: there is duplicates you could just avoid using uniq. It happens because you can have twice the same letter in an array like %w(a c a).

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.