我正在处理作为字符串接收的游戏状态,需要将其转换为 BitBoard。我相信我现在有一个功能可以实现这一点,但想知道如何优化它以加快执行速度?我最初是从一个带有以下想法的循环开始的:
for (i = 0; i < 23; ++i)
{
if (s.at(n) == 'x') set bit[2], // Start with x as there are more x's
else if(s.at(n) == 'W') set bit[0], // W next as W goes first
else set bit[1] // B last
}
但我想我可以展开循环并跳过“i”的比较和递增。这样做之后,我想我可以删除最后一个对“B”的检查,并接受 W | 的赞美。x 并从中减去 4286578688 得到 23 位。这给了我以下代码:
std::string board = "xBWxWxBWxWxxBxxxWxBxxBx"; // String to convert to bitboard
unsigned int bit; // Integer used for parsing values
unsigned int boards[3] {0, 0, 0}; // W in [0], B in [1], & x in [2]
if (board.at(0) == 'x') { boards[2] |= (1 << 22); } else if (board.at(0) == 'W') { boards[0] |= (1 << 22); }
⋅
⋅
⋅
if (board.at(22) == 'x') { boards[2] |= (1 << 0); } else if (board.at(22) == 'W') { boards[0] |= (1 << 0); }
boards[1] = ~(boards[0] | boards[2]) - 4286578688; // Take W's & x's compliment - 4286578688 to get 2163730
printf("%d | %d | %d\n",boards[0], boards[1], boards[2]); // Expected Output: "1351744 | 2163730 | 4873133"
是否有任何其他技巧可以进一步优化此过程以提高速度?我不关心文件大小。
最后,我将如何将 board[W, B, x] 转换回字符串?(例如,玩家“W”在第 22 位添加了一个棋子,结果是boards[] = {1351745, 2163730, 4873132}
。如何将其转换为:board = xBWxWxBWxWxxBxxxWxBxxBW
?)
编辑:我得到了恢复到板的功能,如下所示:
char state[23];
for (int i = 0, j = 22; i < 23; ++i, --j) {
if (boards[2] & (1 << j)) { state[i] = 'x'; } else if (boards[0] & (1 << j)) { state[i] = 'W'; } else { state[i] = 'B'; }
}