In this answer about brute-forcing 2048 AI, a lookup table storing "2048 array shifts" is precomputed to save needless repetitive calculation. In C, to compute this lookup table at compile time, the way I know of is the "caveman-simple solution" where the table itself is generated as another file that is then #include
d, something like this python script to generate lut.include
(replace with 2048-specific code):
#!/usr/bin/python
def swapbits(x):
ret=0
for i in range(8):
if x&(1<<i): ret |= 1<<(7-i)
return ret
print "const uint8_t bitswap[] = {",
print ", ".join("0x%02x"%swapbits(x) for x in range(256)),
print "}"
Is there any cleaner approach? That is, maybe some preprocessor trickery to generate these tables? With C++ this should be possible with constexpr
.