Iterating through numbers by popcount
Posted: 23 Aug 2006, 05:49
I would like to iterate through n-bit numbers starting with a population count of 1 and ending with a population count of n. I need this for use in generating magic keys for bitboard move generation so that I can find the keys if they exist very quickly. For example, to go through all possible 12 bit keys for the worst case keyset (no redundant bits) we will have to only iterate through 64!/( 12! * (64-12)! ) = 3284214703056 magics. (This worst case is rook on A8) If we have redundant bits then the number of magics we will have to iterate though is (64-numredundant)!/( 12! * ((64-numredundant)-12)! ) -- getting small very quickly. Gerd noted that that the number of bits required in the magic (or the complement of the magic) is close to the number of maximum bits in the keyset so I think this kind of generation will end up being very quick for magics that exist.
An example iteration : 4-bit numbers
For 5 bit numbers:
It dosen't matter to me what order each number occurs in a population count group.
How can I iterate like this in C? I'm stumped.
An example iteration : 4-bit numbers
- Code: Select all
0000
0001
0010
0100
1000
0011
0110
1100
0101
1010
1001
1110
1101
1011
0111
1111
For 5 bit numbers:
- Code: Select all
00000
00001
00010
00100
01000
10000
00011
01100
11000
00101
01010
10100
01001
10010
10001
11100
10011
00111
11010
10101
01011
10110
01101
01110
11110
11101
11011
10111
01111
11111
It dosen't matter to me what order each number occurs in a population count group.
How can I iterate like this in C? I'm stumped.