1

I was using bit-shift to generate a powerset of a given numeric string. How can I restrict it to a certain length, say 4, and thus improve the execution time by not finding the subsequences of undesired length.

For ex: if given numeric string is 10292, then only following subsequences are needed: 1029, 102, 109, 029, 0292, etc (only with digits 4,3,2,1).

Following is my code:

scanf("%s", &str); //read numeric string
int n = strlen(str); //find size of string

// loop to find subsequences or powerset
for ( i = 1; i < ( 1 << n ); ++i ) {
    string subseq;
    for ( j = 0; j < n; ++j ) {
        if ( i & ( 1 << j ) ) {
            subseq+=str[j];
        }          
    }

    cout << subseq << endl; //print the subsequence
}
GEOCHET
  • 21,119
  • 15
  • 74
  • 98
kunal18
  • 1,935
  • 5
  • 33
  • 58

1 Answers1

0

Just put a filter in front of the print statement.

if (subseq.length() <= 4) cout<<subseq<<endl;
Keith Randall
  • 22,985
  • 2
  • 35
  • 54
  • I thought of it; even I tried. But it won't save the precious time to calculate subsequences of undesired length, which is what I want to do. – kunal18 Aug 03 '12 at 21:11
  • Ah, you want it to be *fast*. You should add that requirement to the question. – Keith Randall Aug 03 '12 at 21:13
  • 1
    @StalinSubramaniam: Well in that case I think you need to drop your 'bit-shift' method and switch to a recursive approach. A recursive approach can easily count the number of characters included so far and stop when that reaches four. Plus a recursive method wouldn't be limited by the number of bits in an integer. – jahhaj Aug 03 '12 at 21:14