Permutations of single array in expected array of arrays

Viewed 49
new_variant_permutations = all_value_arrays[1..].inject(all_value_arrays[0]) { |m, v| m.product(v).map { |perm| perm.flatten.sort } }

This line if given an all_value_arrays which is basically an array of arrays like [[1,2],[3,4]] returns possible permutations such as [[1,3],[1,4],[2,3],[2,4]] However if all_value_arrays is a single array inside an array like [[1,2,3,4]], instead of getting my expected [[1],[2],[3],[4]] I get [1,2,3,4] and this causes a problem with my code later on How can i avoid this happening and maintain the consistency of array of arrays as in my first example? TIA

2 Answers

This one liner should do what you're asking for (return an array of arrays representing the cartesian product of the input arrays).

all_value_arrays.reduce(&:product).map { |perm| [perm].flatten }
def doit(arr)
  arr.first.product(*arr.drop(1))
end
doit [[1,2],[3,4],[5,6]]
  #=> [[1, 3, 5], [1, 3, 6], [1, 4, 5], [1, 4, 6],
  #    [2, 3, 5], [2, 3, 6], [2, 4, 5], [2, 4, 6]]
doit [[1,2,3,4]]
  #=> [[1], [2], [3], [4]]
Related