3
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

7
  • Why do you expect the output [[1],[2],[3],[4]] with the input [[1,2,3,4]]? Are you trying to return all permutations of any length? Commented Apr 17, 2021 at 21:10
  • I'm trying to return permutations of my entry arrays that include one and exactly one value from the values in each of my entry arrays. Commented Apr 17, 2021 at 21:12
  • I have hotfixed by succeeding with new_variant_permutations = new_variant_permutations.map { |entry| entry.is_a?(Array) ? entry : [entry] } but I'd rather fix my initial code. Commented Apr 17, 2021 at 21:12
  • 1
    Whoops. Try .reduce(&:product).map { |perm| [perm].flatten } instead. Commented Apr 17, 2021 at 21:29
  • 1
    That seems to work for both my cases yes! thanks! Commented Apr 17, 2021 at 21:31

2 Answers 2

1

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 }
Sign up to request clarification or add additional context in comments.

Comments

0
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]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.