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
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With