查找存储在long位中的最后一个int(1-9)(每个int由4位表示)

时间:2015-02-12 02:28:12

标签: java c++ bit-manipulation bit-shift

我正在开发一个Tic-Tac-Toe AI,并希望使用游戏引擎提供的长时间找到最后一步(Opponents在当前回合之前的最后一步)。

每个空格由单个数字整数1-9表示(我将从0到0加减1,对于板外运动加9,存储在长为0xF)。

0xE用于表示NULL,但我的程序会将其视为板外移动。

以下是游戏状态的编码方式:

Used to encode game State, first 4 bits are first move, second 4 bits second move, (4 * 9 = 36 bits) bits 33-36 are the last Move. Each move is the coordinate singleton + 1, therefore the tictactoe board is recorded as...
  1 |  2 | 3
  4 |  5 | 6
  7 |  8 | 9

Normal equation for singleton is row*3+col, but you cannot record a state as 0, therefore game state moves are row*3+col + 1, note difference Coordinate singleton is 0..8, board game state position is 1..9;
 1 | 2 | 3
 4 | 5 | 6
 7 | 8 | 9



The game state 0x159, X first move 9; O move 2 is 5;move 3 X is 1


 X _ _ 
 _ O _
 _ _ 9



 Sets off board set all 4 bits (aka 0xf).


e.g., 0x12f45, On X's second move (game move 3)
 X picked a Coordinate outside the tictactoe range.


Duplicate guesses onto occupied square are just saved


e.g., 0x121 implies X has used position 1 on both his
 first and second move


Null coordinate usually caused by exception is saved as 0xE


e.g., 0x1E3; implies on game move 2, O first move, O throw an exception
 most likely causes index array out of bounds

截至目前,以下是我如何使用引擎的游戏状态找到最后一步:

private int LastMoveFinder(final Board brd, int move)
{
    char prevMove = Long.toHexString(brd.getGameState()).charAt(0);

    if(prevMove == 'f' || prevMove == 'e')
        return 9;
    else
        return Character.getNumericValue(prevMove) - 1;
}

但是,我确信有一种更快的方法(性能明智)使用某种bithift方法找到最后一步,因为我们的AI将相互测试速度(nanoSec / move)和win-tie-损失率。

我已经阅读过bithifting并在stackoverflow上搜索了像我这样的问题的答案,但是我试图在我的程序中实现的任何东西都没有用。

我确信我错过了一些简单的东西,但还没有采用涵盖位移和掩蔽的方法,所以我有点不知所措。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

你可以通过AND'来获得4位int,其中位移掩码0xf向左移动4 * moveNumber位。然后,将结果右移4 * moveNumber位以获得int,并将移动逻辑应用于该int。修改后的方法是:

/**
   Assumes moveNumber is 0 indexed.
 */
private int LastMoveFinder(final Board brd, int moveNumber)
{
    int moveMask = 0xf << (4 * moveNumber);
    int prevMove = (brd.getGameState() & moveMask) >>> (4 * moveNumber);

    if (prevMove == 0xf || prevMove == 0xe) {
        return 9;
    } else {
        return prevMove - 1;
    }
}