如何生成多个数组的所有排列/组合? [英] How can I generate all permutations / combinations of multiple arrays?
本文介绍了如何生成多个数组的所有排列/组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的目标很简单,我正在尝试为数据库中的产品生成所有可能组合的列表.
My goal is simple, I am trying to generate a list of all possible combinations for a product in a database.
例如;产品选项如下
- 产品选项:颜色/值:红色、绿色、蓝色
- 产品选项:尺寸/值:小号、中号、大号、XL
- 产品选项:风格/价值观:男性、女性
我希望能够自动生成所有 3 个的每个组合:
I want to be able to auto generate every single combination of all 3:
Small, Red, Mens
Small, Green, Mens
Small, Blue, Mens
etc
无论我将 2、3、4 还是 5 个数组传递给它,我都需要该函数工作.
I need the function to work whether I pass 2,3,4 or 5 arrays into it.
我进行了大量研究并阅读了以下文章,但未能实现我的目标.
I've done quite a bit of research and came across the following articles but have been unable to accomplish my goal.
我找到的文章如下:
推荐答案
改编来自 Eric Lippert 的博客关于笛卡尔积:
Adapting code from Eric Lippert's blog on Cartesian products:
Private Function CartesianProduct(Of T)(ParamArray sequences As T()()) As T()()
' base case:
Dim result As IEnumerable(Of T()) = {New T() {}}
For Each sequence As var In sequences
Dim s = sequence
' don't close over the loop variable
' recursive case: use SelectMany to build the new product out of the old one
result = From seq In result
From item In s
Select seq.Concat({item}).ToArray()
Next
Return result.ToArray()
End Function
用法:
Dim s1 As String() = New String() {"small", "med", "large", "XL"}
Dim s2 As String() = New String() {"red", "green", "blue"}
Dim s3 As String() = New String() {"Men", "Women"}
Dim ss As String()() = CartesianProduct(s1, s2, s3)
这篇关于如何生成多个数组的所有排列/组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文