In response to Shadowdarke
Shadowdarke wrote:
Lummox JR wrote:
The switch can be taken out because diagonal directions are easy to spot: As long as 2 bits are set in the number, you have a diagonal. My test for this is n&n-1 (which is n&(n-1) since - has a higher precedence); in n-1, the lowest bit of n is switched off and all bits to its right (if any) are switched on, then the binary and will cancel out that lowest bit, leaving any that remain.

if(d&d-1) // diagonal

Beautiful! I used a messy "if(dir in list(NORTHEAST, NORTHWEST, SOUTHEAST, SOUTHWEST))" to detect a diagonal, cursing myself and knowing there had to be a better way. If you'll excuse me, I have a few libraries to update. :)

I forget the method I used in my first project but it was truly heinous. Once I realized directions were done as bit flags, a lot of things became simpler.

The n&(n-1) method is one I figured out years ago in college. I believe the day that occurred to me I was trying to keep awake in a C class (I already knew C). Once I hit on that property of n-1, several formulas (which I've never fully explored) clicked into place:

Turn off lowest 1 bit: n&(n-1)
Side effect: If n&(n-1) != 0, n has 2+ 1 bits
Bit mask for lowest 1 bit: n^(n&(n-1))
Turn on lowest 0 bit: n|(n+1)
Bit mask for lowest 0 bit: n^(n|(n+1))
Side effect: If n&(n-1) != MAX_WORD, n has 2+ 0 bits

The +1 and -1 tricks are most useful, it seems to me, in any case where the bits do or mean something sequentially.

Lummox JR
Page: 1 2