查找存储在长位中的最后一个int(1-9)(每个int由4位表示)
Find last int (1-9) stored in long of bits (each int represented by 4 bits)
我正在开发一个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;
}
}
相关文章:
- 在 std::无符号字符的向量处存储 int 的十六进制表示形式
- 使用 int 表示浮点除法 C++
- 是否可以保证按字节的零 int 是零的表示形式?
- 使用 int 指针的浮点数的位表示形式
- 如何检查 int 变量是否包含合法(非陷阱表示)值?
- 为表示一个或多个操作的C++函数的int参数寻找类型安全的替换
- 运行时错误:有符号整数溢出:964632435 * 10 无法在类型 'int' 中表示
- 在二进制表示中将二进制 std::string 转换为 int
- 由INT数据类型(低,高)结构表示的双数据类型
- 表示给定"int"的最小位数
- 为什么不能将 int(表示 ASCII 字符)转换为 std::字符串,而没有大括号环绕在 int 周围?
- 使用inet_pton()获取IPv4地址的无符号int表示形式
- 使用向量<对<字符串,int > >表示哈希表
- C/C++ int[] vs int*(指针与数组表示法).有什么区别
- 查找存储在长位中的最后一个int(1-9)(每个int由4位表示)
- c++帮助设计类ConstArray和Array,它们表示一种int值的动态数组
- 将 int 的所有字节设置为(无符号字符)0,保证表示零
- x[0] == 1 在 C++11 中表示 1 个常量表达式,当 x 是常量 int[]
- 在c++中将N位int表示为十六进制
- 将char数组转换为int表示