Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Permutations of single array in expected array of arrays

Tags:

ruby

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

like image 838
Omar Hussein Avatar asked Dec 31 '25 11:12

Omar Hussein


1 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 }
like image 145
Ray Hamel Avatar answered Jan 03 '26 16:01

Ray Hamel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!