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,BDY和BDZ.我们有一个用户用来生成上述表达式的UI.在后端,我们需要生成不同的组合,以便更容易地匹配一组元素,如ACX,ACY等.
具有AND的组的数量不固定,并且每个AND组内的元素的大小也不同.
关于如何完成这项工作的想法是什么?我试图用递归编写它,并寻找其他人是否有更聪明的答案或是否存在库.
尝试:
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)
您的问题特别感兴趣的是第三个例子.
| 归档时间: |
|
| 查看次数: |
94 次 |
| 最近记录: |