如何在表达式中分发元素?

sum*_*mit 2 ruby algorithm distribution

给出一个表达式:

(A OR B) AND (C OR D) AND (X OR Y OR Z)
Run Code Online (Sandbox Code Playgroud)

我需要分发和生成的组合ACX,ACY,ACZ,ADX,ADY,ADZ,BCX,BCY,BCZ,BDX,BDYBDZ.我们有一个用户用来生成上述表达式的UI.在后端,我们需要生成不同的组合,以便更容易地匹配一组元素,如ACX,ACY等.

具有AND的组的数量不固定,并且每个AND组内的元素的大小也不同.

关于如何完成这项工作的想法是什么?我试图用递归编写它,并寻找其他人是否有更聪明的答案或是否存在库.

the*_*Man 6

尝试:

AB = %w[A B]
CD = %w[C D]
XYZ = %w[X Y Z]

AB.product(CD, XYZ).join(&:map)
Run Code Online (Sandbox Code Playgroud)

返回一个数组,如:

[
  "ACX",
  "ACY",
  "ACZ",
  "ADX",
  "ADY",
  "ADZ",
  "BCX",
  "BCY",
  "BCZ",
  "BDX",
  "BDY",
  "BDZ"
]
Run Code Online (Sandbox Code Playgroud)

Ruby的Array.product文档说:

------------------------------------------------------------------------------
  ary.product(other_ary, ...)                -> new_ary
  ary.product(other_ary, ...) { |p| block }  -> ary


------------------------------------------------------------------------------

Returns an array of all combinations of elements from all arrays. The length of
the returned array is the product of the length of self and the argument
arrays. If given a block, product will yield all combinations and
return self instead.

  [1,2,3].product([4,5])     #=> [[1,4],[1,5],[2,4],[2,5],[3,4],[3,5]]
  [1,2].product([1,2])       #=> [[1,1],[1,2],[2,1],[2,2]]
  [1,2].product([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]]
  [1,2].product()            #=> [[1],[2]]
  [1,2].product([])          #=> []
Run Code Online (Sandbox Code Playgroud)

您的问题特别感兴趣的是第三个例子.

  • 只有当它打破时才提供链接是没有价值的.我提供了一个链接和相关部分,这是我们应该做的. (2认同)
  • 由于各种原因,该链接在过去已经下降,并最终返回.它比过去更稳定,但是,根据对SO的共识,我们不应该只使用链接,而是参考直接内容.我喜欢走路."[其他地方只包含链接的答案真的是"好的答案"吗?](http://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers )" (2认同)