CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Aug 2010
    Posts
    20

    Get sub sets from list

    Hi,
    Does anybody can tell me how can I select all sub set from list.
    it means that if i have a list that contains values {1,2,3,4}
    I want to get all those sub list
    {1,2,3,4,12,13,14,23,24,34,123,124,234,1234}
    I try to make it in many ways but it fails again and again.
    code sample can help very much.
    Thanks.

  2. #2
    Join Date
    Jan 2006
    Location
    Fox Lake, IL
    Posts
    15,007

    Re: Get sub sets from list

    Search for COMBINATION'S. A simple loop can compute what you want.
    David

    CodeGuru Article: Bound Controls are Evil-VB6
    2013 Samples: MS CODE Samples

    CodeGuru Reviewer
    2006 Dell CSP
    2006, 2007 & 2008 MVP Visual Basic
    If your question has been answered satisfactorily, and it has been helpful, then, please, Rate this Post!

  3. #3
    Join Date
    Feb 2011
    Location
    United States
    Posts
    1,016

    Re: Get sub sets from list

    This sounds like homework, so I'll try to only sketch the solution:

    For a set of N elements there are 2^N subsets (or 2^N - 1, if you don't include the null set). An insight is that you can order them by assigning each subset a binary number. For, for the set {1, 2, 3, 4} you can denote the subset that includes the 2nd and 4th element as:

    { 2, 4 } = 0101

    And in binary 0101 is 5, so this set corresponds to the number 5 and an element is included if there is a ONE at it's position in the binary representation of the number.

    You can perform a loop to see if you should include an element like:

    Code:
    int subsetIDNumber = 0101;
    for(int i = 0; i < 4; i++)
    {
        if( subsetIDNumber & 1 == 1 )
            //Include the element
        else
            //Don't include the element
    
        subsetIDNumber >>= 1;  //Bitwise shift the subsetIDnumber right
    }
    Thus you can loop over them like...

    Code:
    int twoToTheNumElements = 16;
    for(int i = 1; i <= twoToTheNumElements; i++)
    {
        //Construct the subset corresponding to the number i
    }
    Hope that helps. Good luck.
    Last edited by BioPhysEngr; April 11th, 2011 at 12:44 AM. Reason: forgot to use code tags... dagnabbit!
    Best Regards,

    BioPhysEngr
    http://blog.biophysengr.net
    --
    All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured