Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

vb.net - 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.

So for example; the product options are as follows

  • Product Option: Color / Values: Red, Green, Blue
  • Product Option: Size/ Values: Small, Med, Large, XL
  • Product Option: Style / Values: Men, Women

I want to be able to auto generate every single combination of all 3:

Small, Red, Mens
Small, Green, Mens
Small, Blue, Mens
etc

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.

The articles I found are as follows:

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Usage:

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...