Given a bitmask where the set bits describe where another number can be one or zero and the unset bits must be zero in that number. What’s a good way to iterate through all its possible values?
For example:
000 returns [000]
001 returns [000, 001]
010 returns [000, 010]
011 returns [000, 001, 010, 011]
100 returns [000, 100]
101 returns [000, 001, 100, 101]
110 returns [000, 010, 100, 110]
111 returns [000, 001, 010, 011, 100, 101, 110, 111]
The simplest way to do it would be to do it like this:
void f (int m) {
int i;
for (i = 0; i <= m; i++) {
if (i == i & m)
printf("%d\n", i);
}
}
But this iterates through too many numbers. It should be on the order of 32 not 2**32.
There’s a bit-twiddling trick for this (it’s described in detail in Knuth’s “The Art of Computer Programming” volume 4A §7.1.3; see p.150):
Given a mask
maskand the current combinationbits, you can generate the next combination with…start at 0 and keep going until you get back to 0. (Use an unsigned integer type for portability; this won’t work properly with signed integers on non-two’s-complement machines. An unsigned integer is a better choice for a value being treated as a set of bits anyway.)
Example in C:
which gives:
(…and I agree that the answer for
000should be[000]!)