This is the code which generates possible permutation using bit masking. I am having problem in understanding how is it executing after this condition when i = 2 , bit = 4 , mask = 7.
when bit is 4 and mask is 7 so condition (bit & mask) == true So it will continue .How i = 2 again ? and how mask becomes 1 when Mask will change when it will execute recurse(....)
#include <iostream>
#include <string>
using namespace std;
void recurse(string s, int mask = 0,string out = "")
{
int n = s.length();
if (out.length() == n) cout << ' ' << out<<endl;
for (int i = 0; i < n; i++) {
cout<<"I:"<<i<<"=>";
unsigned bit = 1 << i;
cout<<bit<< " -> " <<mask<<endl;
cout<<"cond:"<<(mask & bit)<<endl;
if (mask & bit) continue;
cout<<out+s[i]<<endl;
recurse(s, mask | bit, out + s[i]);
}
}
int main()
{
string test = "red";
recurse(test);
cout << endl;
return 0;
}
Output:
I:0=>1 -> 0
cond:0
r
I:0=>1 -> 1
cond:1
I:1=>2 -> 1
cond:0
re
I:0=>1 -> 3
cond:1
I:1=>2 -> 3
cond:2
I:2=>4 -> 3
cond:0
red
red
I:0=>1 -> 7
cond:1
I:1=>2 -> 7
cond:2
I:2=>4 -> 7 <===== here when bit is 4 and mask is 7 so condition (bit & mask) == true
cond:4 So it will continue .How i = 2 again ? and how mask becomes 1 when Mask will change when it will execute recurse(....)
I:2=>4 -> 1
cond:0
rd
I:0=>1 -> 5
Aucun commentaire:
Enregistrer un commentaire