将阵列组合成所有可能值组合的阵列的单线算法?

时间:2011-01-22 21:57:13

标签: ruby algorithm

我不确定我是否完全形成了问题,但我想要做的基本上是这样的:

# 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"]]

数组的顺序始终相同,因此每个数组的反向(例如[b, a])不包含在结果中。

这是什么以及实现这一目标的有效方法是什么?

我看到Array#permutation,但那不是......

这有望适用于任意数量的数组和值:combine(*arrays)

谢谢!

更新

以下是我正在寻找的更好的例子:

(x | y).combination(x.length).to_a产生以下内容:

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

我正在寻找的实际结果是:

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

或者如果它是一个更长的阵列:

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

有什么想法吗?

3 个答案:

答案 0 :(得分:5)


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

对于几个阵列:


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

答案 1 :(得分:3)

(x | y ).combination(x.length).to_a

答案 2 :(得分:0)

def combine(*arrays)
  head, *tail = arrays.transpose
  head.product(*tail)
end

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

侧面说明题外话:这是一个场景,您可以在其中了解函数式语言使函数成为重要的东西。你必须在OOP中调用一个对象的方法这一事实迫使你 - 在这种情况下 - 设计得到他们的头/尾。当你将product作为函数时,例如在Python中,你没有这种问题:

itertools.product(*zip(*arrays))