0

So I've been wracking my brain over this for a while and, while the code works, it prints it in the absolute wrong order. I feel like I'm missing something so I could use an extra pair of eyes.

void recursiveBitPatterns(ArrayList<String> subsets, int n)
{
    if (n==1)
    {
        subsets.add("0");
        subsets.add("1");
        return;
    }
    recursiveBitPatterns(subsets, n-1);
    int asize = subsets.size();
    for(int i=0; i<asize; i++)
    {
        String nsub = subsets.get(i);
        subsets.set(i, nsub +"0");
        subsets.add(nsub + "1");
    }
}

It seems to be setting the second element of the arraylist to 1 but not overwriting it in the loop.

This prints:

000 100 010 110 001 101 011 111

Any help would be appreciated

4
  • 1
    What is the code supposed to be doing? What input generated that output and what output did you expect? Commented Oct 31, 2014 at 20:50
  • Did you mean "print all subsets from a set of N elements"? Commented Oct 31, 2014 at 20:54
  • It's LSB first instead of MSB first. Commented Oct 31, 2014 at 20:56
  • @VitJaybird Already I understood what you want to show. Already I modified you code, look below. Commented Oct 31, 2014 at 22:20

2 Answers 2

0

You code would look like.

void recursiveBitPatterns(ArrayList<String> subsets, int n)
{
    if (n==1)
    {
        subsets.add("0");
        subsets.add("1");
        return;
    }
    recursiveBitPatterns(subsets, n-1);
    int asize = subsets.size();
    for(int i=0; i<asize; i++)
    {
        String nsub = subsets.get(i);
        subsets.set(i, "0" + nsub);
        subsets.add("1" + nsub);
    }
}

This prints:

000 001 010 011 100 101 110 111
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I figured I just had a small issue in my code. This helps a lot!
0

As far as I read in your code you are trying to generate all possible subsets from a set of N elements.

let subsets to be the arraylist where the subsets will be stored.

void gen(int N, int subset)  {
    if ( N < 0 ) {
        subsets.add( Integer.toBinaryString(subset) );
        return;
    }

    gen(N - 1, subset);
    gen(N - 1, subset | (1 << N) );
}

call it:

gen( sizeOfSet - 1, 0 );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.