16

Questions similar to this have been asked before on SO, but they're not quite what I need and I can't seem to arrive at my solution through altering/modifying those approaches.

In any case, I have an array of arrays, as follows:

b= [["1"],["2"],["3"],["4"],["5"],["6"]]

(If it makes it easier to arrive at a solution, b can also be a one dimensional array, as follows: ["1","2","3","4","5","6"]. Either type of input works for my needs.)

and I would like to generate the following:

[["123456"],["213456"],["312456"],...] 

where each array in the output array is a unique permutation of the six numbers. I would also take it as a single array (e.g., ["123456", "213456",...]). The order of the output isn't particularly important as long as each entry is unique and no number repeats in a string (e.g., "112345" isn't allowed). All 6 numbers must also be used in each entry, so I'm not interested in incremental output like "123", either.

As much as this sounds like it, this isn't a homework problem. I could brute for this thing and get the output I need. I just feel like there has to be a better, more elegant, solution.

1
  • 3
    You may find more pertinent information comparing the definitions of "combination" versus "permutation". Your particular issue appears to be generating permutations, not combinations, of a set. Commented Jul 25, 2012 at 15:44

4 Answers 4

39

With Array#permutation:

permutations = (1..6).to_a.permutation.map(&:join)
# ["123456", "123465", "123546", ..., "654312", "654321"]
Sign up to request clarification or add additional context in comments.

Comments

19

Ruby does this natively :) From the ruby documentation :

a = [1, 2, 3]
a.permutation.to_a     #=> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
a.permutation(1).to_a  #=> [[1],[2],[3]]
a.permutation(2).to_a  #=> [[1,2],[1,3],[2,1],[2,3],[3,1],[3,2]]
a.permutation(3).to_a  #=> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
a.permutation(0).to_a  #=> [[]] # one permutation of length 0
a.permutation(4).to_a  #=> []   # no permutations of length 4

http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-permutation

Comments

1

You should definitely have a look at Permutation Gem. Example from documentation

perm = Permutation.new(3)
# => #<Permutation:0x57dc94 @last=5, @rank=0, @size=3>
colors = [:r, :g, :b]
# => [:r, :g, :b]
perm.map { |p| p.project(colors) }
# => [[:r, :g, :b], [:r, :b, :g], [:g, :r, :b], [:g, :b, :r], [:b, :r, :g],
#  [:b, :g, :r]]

UPDATE

If you are using Ruby > 1.8.6, Array.permutation is built in.

Comments

1

This should do it:

b.permutation.to_a.collect! { |i| i = [i.flatten.join] }

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.