How to Generate Permutations from Multi-Dimensional Array?

I want generate permutations from a given multi-dimensional array.
Unfortunately, the code I’ve put together (see below) does not generate
the permutations correctly; the code treats the value arrays as pairs
rather than alternatives. Anyone know how to get the desired results?

For example, given the array:

[ {id: 1, value: [’$’, ‘%’]}, {id: 2, value: [‘a’, ‘b’, ‘c’]}, {id: 3,
value:
[‘1’]} ]

I want:

[[$, a, 1], [%, a, 1], [$, b, 1], [%, b, 1], [$, c, 1], [%, c, 1]]

But instead I’m getting:

[[["$", “%”], [“a”, “b”, “c”], [“1”]], [["$", “%”], [“1”], [“a”, “b”,
“c”]], [[“a”, “b”, “c”], ["$", “%”], [“1”]], [[“a”, “b”, “c”], [“1”],
["$", “%”]], [[“1”], ["$", “%”], [“a”, “b”, “c”]], [[“1”], [“a”, “b”,
“c”], ["$", “%”]]]

The code:

data = [ {id: 1, value: [’$’, ‘%’]}, {id: 2, value: [‘a’, ‘b’, ‘c’]},
{id: 3, value: [‘1’]} ]

values = data.collect { |m| m[:value] }
perm = values.permutation.to_a

p perm

There is no easy solution for n arrays. You need some nasty recursion.
Here is one solution:

http://snippets.dzone.com/posts/show/3332

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs