My goal is to iterate through arrangements with 10 binary characters (each T or F) such that exactly 5 of them are Ts.
This is equivalent to generating a subset of 5 indices from 10 total indices; those 5 will dictate the location of the Ts.
I don’t want to iterate through all 2^{10} subsets, then see which ones have exactly 5 Ts. Instead, I only want to generate the \binom{10}{5} subsets/arrangements with the desired property.
How can I achieve this using:
- Recursion. I tried this, but it seems to iterate through all subsets, and it doesn’t work:
void gen_MY(int i=0, int t=0){ // i = current index, t = Ts so far
if(t==5){
keys.push_back(ANS);
return;
}
if(i==10) return;
ANS[i] = 'T'; gen_MY(i+1, t+1);
ANS[i] = 'F'; gen_MY(i+1, t);
}
- Bitmasks. Is it possible to generate a bitset with exactly 5 1s? It is possible to iterate through all subsets:
for(int mask=0; mask < (1<<n); ++mask){
int cnt = 0;
for(int j=0; j<n; j++){
if(mask & (1<<j)) cnt++;
}
if(cnt==5) keys.push_back(mask);
}
However, this isn’t what I want. Please read the sentences above for an explanation.
- Permutations. I know I can do this using
next_permutation()
.
MY = "FFFFFTTTTT";
do{ keys.push_back(MY) }
while(next_permutation(begin(MY), end(MY)));
I know how to implement permutation with recursion using a cnt
map. However, I need to make sure the recursion doesn’t regard the 5 Fs as distinct or the 5 Ts as distinct. Can you please post your code for achieving permutation with recursion in this manner?
Please post a sample code for each of the 3 methods listed above. Thank you!