2

I have tried writting the following function to generate all combinations of a string by translating the algorithm from my algorithm text. But it keeps print entire string in the output for all the combinations.

len = strlen(str);
for(i=0;i<pow(2,len);i++) 
{
        for(j=0;j<len;j++) 
        {
                if(i && (0x1 << j)) 
                {
                        cout<<str[j];
                }
        }
        cout<<endl;
}

Thanks you all.

user664982
  • 51
  • 5
  • 1
    Since this is C++, prefer to use `std::string` to `char *`. Obtaining the length of a `std::string` is faster than scanning for `'\0'` in a `char *`. Also, `std::string` is safer and can grow. – Thomas Matthews Mar 17 '11 at 19:45
  • 1
    @Thomas Matthews: You do realize that `(len * len)` is not a substitute for `pow(2, len)`, right? – Blastfurnace Mar 18 '11 at 04:46
  • 1
    @Blastfurnace: Sorry, my bad. Got parameters mixed up. Removed comment about `pow(2, len) == (len * len)`. – Thomas Matthews Mar 18 '11 at 18:35

1 Answers1

7

Since you want to check if the jth bit is set in variable i you need to use the bitwise & operator and not the logical &&:

if(i && (0x1 << j))
     ^^
codaddict
  • 445,704
  • 82
  • 492
  • 529
  • You'll find this useful: http://stackoverflow.com/questions/5051349/what-is-the-difference-bettween-bitwise-and-and-logical-and – codaddict Mar 17 '11 at 19:57