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

Find last int (1-9) stored in long of bits (each int represented by 4 bits)

本文关键字:int 表示 4位 每个 最后一个 存储 查找      更新时间:2023-10-16

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

每个空格由一个个个位数的整数1-9表示(我将从中减去1得到0-8的移动,加上存储在0xF中的板外移动的9)。

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;
}

但是,我相信有一种更快的方法(从性能角度来看)可以使用某种位移方法找到最后一步,因为我们的人工智能将在速度(nanoSec/move)和胜负比方面进行测试。

我读过比特移位的文章,并在stackoverflow到处寻找类似我的问题的答案,但我试图在我的程序中实现的任何东西都没有奏效。

我确信我错过了一些简单的东西,但还没有上过比特移位和掩蔽的课程,所以我有点不知所措。

谢谢你的帮助。

您可以通过将int的位掩码0xf左移4*moveNumber位进行"与"运算来获得它的4位。然后,将结果右移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;
    }
}