0

In order to represent the state of a 2D board game, I am using bitboards with 16bits unsigned integers. The state is encoded with 1 for piece presence and 0 else.

What is the bitboard way to count the number of pieces having at least one adjacent piece horizontally, vertically or diagonally ?

The algorithm I found (very simplified) is:

total = 0
for each bitIndex in bitscanForward(bitboard)
    total += bitPopCount(bitboard & (ADJACENT_MASK << bitIndex))
return total
  • bitScanForward function returns index of first bit and set it to 0
  • bitPopCount function returns the number of bits

The only constraint is that boards are m rows x m columns with m <= 8.

Is there a way to accomplish that without looping over bits ?

Loheek
  • 1,865
  • 17
  • 28

1 Answers1

2

Get a mask that has a bit set IFF it has a piece on it and some adjacent piece (ie there is a piece directly to the left, or to the right, or up, or down, or diagonally):

mask = board & (left(board) | right(board) | up(board) | down(board) |
                left(up(board)) | left(down(board)) |
                right(up(board)) | right(down(board)))

Then just count it.

The key is obviously the implementation of the board "shifts", but they are really simple. Your choice of what a direction means in terms of bits may differ depending on the order in which you pack bits in a board. For example for 4x4 boards packing in some order that seemed to make sense:

left(board)  = (board & 0x7777) << 1
right(board) = (board & 0xEEEE) >> 1
up(board)    = board << 4
down(board)  = board >> 4
harold
  • 61,398
  • 6
  • 86
  • 164