Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 714
  • Last Modified:

generating a series for all 2 power n combinations in vb.net

I have n items and each item can be assigned a 1 or a 2. So I would like to get the matrix result that would generate all possible combinations.
For eg. if n= 3 , then the possible outcomes are : I  need an algorithm that can generate this series for n . Please help thanks. ideally i would like to store the result in a datatable

1 1 1
1 1 2
1 2 1
2 1 1
2 1 2
1 2 2
2 2 1
2 2 2
0
TrialUser
Asked:
TrialUser
  • 3
  • 2
2 Solutions
 
jagssiduralaCommented:
Logic is

2^0 2^0 2^0
2^0 2^0 2^1
2^0 2^1 2^0
2^0 2^1 2^1
2^1 2^0 2^0
2^1 2^0 2^1
2^1 2^1 2^0
2^1 2^1 2^1

The power to the num 2 is binary seris

0
 
AmbusyCommented:
        Dim HighestValue As Integer = 2 ' max value
        Dim NrOfValues As Integer = 3 ' nr of values in one result
        Dim Values(NrOfValues) As Integer
        Dim i As Integer
        For i = 0 To NrOfValues - 1
            Values(i) = 1
        Next
        Values(NrOfValues - 1) = 0 ' to generate first as ALL 1
        For i = 1 To HighestValue ^ NrOfValues
            Values(NrOfValues - 1) += 1
            For j As Integer = NrOfValues - 1 To 0 Step -1
                If Values(j) > HighestValue Then
                    Values(j) = 1
                    Values(j - 1) += 1
                End If
            Next
            Dim Result As String = ""
            For j As Integer = 0 To NrOfValues - 1
                Result = Result & CStr(Values(j))
            Next
            Debug.WriteLine(Result)
        Next

Open in new window

0
 
TrialUserAuthor Commented:
Thank you both for the suggestoins. Both the suggestions are great and made me understand the concept behind.

Ambusy, the code you provided just works great and does exactly what I wanted.

Just one question, if I change     HighestValue , and NrOfValues  then this logic should just work for any number of items and any number of possible values for each item right?

thanks again.
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
AmbusyCommented:
Exactly, that's why I wrote them as variables. I tested them with values in a textbox to be certain it workes.
0
 
AmbusyCommented:
If my solution is correct, please accept it.
0
 
TrialUserAuthor Commented:
the solution works great. does exactly what I want
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now