Eli Hooten Eli Hooten - 5 months ago 18
Ruby Question

Ruby all possible permutations of an array of arrays (one liner?)

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,
can also be a one dimensional array, as follows:
. Either type of input works for my needs.)

and I would like to generate the following:


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


With Array#permutation:

permutations = (1..6).to_a.permutation.map(&:join)
# ["123456", "123465", "123546", ..., "654312", "654321"]