A single-layer algorithm for combining arrays into arrays of all possible combinations of values?

Not quite sure that my question is fully formed, but what I'm trying to do is basically this:

# where the indices correspond to attributes fore example:
# [type, status]
x = %w(a b)
y = %w(c d)
combine(x, y) #=> [["a", "b"], ["a", "d"], ["c", "a"], ["c", "b"]]

The order of the array is always the same, so the opposite of each, for example [b, a], is not included in the result.

What is it called and what is an effective way to implement this?

I see Array # permutation , but it’s not really ...

This, we hope, will work for any number of arrays and values: combine(*arrays)

Thank!

Update

Here is the best example of what I'm looking for:

This (x | y).combination(x.length).to_acauses the following:

x = ["front_door", "open"]
y = ["back_door", "closed"]
(x | y).combination(x.length).to_a
=> [["front_door", "open"], ["front_door", "back_door"], ["front_door", "closed"], ["open", "back_door"], ["open", "closed"], ["back_door", "closed"]] 

The actual result I'm looking for is:

=> [["front_door", "open"], ["front_door", "closed"], ["back_door", "open"], ["back_door", "closed"]]

Or if it was a longer array:

x = ["house", "front_door", "open"]
y = ["building", "back_door", "closed"]
compute(x, y)
=> ["house", "front_door", "open"], ["house", "back_door", "open"], ["house", "front_door", "closed"], ["house", "back_door", "closed"], ["building", "front_door", "open"], ["building", "back_door", "open"], ["building", "front_door", "closed"], ["building", "back_door", "closed"]

Any ideas?

+3
source share
3

x.zip(y).reduce(:product).map(&:flatten)

:


x.zip(y,z,w).reduce(:product).map(&:flatten)

+5
(x | y ).combination(x.length).to_a
+3
def combine(*arrays)
  head, *tail = arrays.transpose
  head.product(*tail)
end

combine(x, y)
combine(x, y, z, ...)

Side Note Rejection: This is one of the scenarios in which you understand that functional languages ​​make important functions important. The fact that you have to call an object method in OOP makes you - in this case - inventively get your head / tail. If you have productas a function, for example, in Python, you have no such problems:

itertools.product(*zip(*arrays))
0
source

Source: https://habr.com/ru/post/1787208/


All Articles