如果我有一个64长度的java数组i [],有没有一种快速的方法可以找出该数组中的每个位置是否都是"满",而不是循环整个数组?我正在编写一个Reversi AI,我需要知道整个阵列是否已满.
Gra*_*and 10
保留一个类型的标志变量long(64位),并通过设置或清除相关位来使用它来跟踪哪些数组条目是"满".(您需要将其与数组条目保持同步.)
如果您1为每个位使用一个值来表示相关单元格已满,则可以通过比较标志变量来快速判断整个数组是否已满-1L.
示例实现
int[] grid = new int[64];
long full = 0L;
// place a piece at a certain grid position
grid[17] = 1; // pretend 1 is the code for black
full |= 1L << 17; // set bit 17 in our "full" tracker
// is the grid full?
if (full == -1L)
// yes it is!
else
// no it isn't
Run Code Online (Sandbox Code Playgroud)
您可以更加狡猾,并使用flags变量来跟踪每个单元格的颜色,这样您就可以完全避免使用数组.一个变量跟踪给定的单元是否被占用,另一个跟踪颜色(0表示白色,1表示黑色,比方说).
long colour = 0L;
long full = 0L;
// set position 17 to white
colour &= ~(1L << 17); // clear the bit (white)
full |= (1L << 17); // set it to occupied
// set position 42 to black
colour |= (1L << 42); // set the bit (black)
full |= (1L << 42); // set it to occupied
// is position 25 occupied?
if ((full & (1L<<25)) != 0) {
// yes, but what colour?
if ((colour & (1L<<25)) != 0)
// black
else
// white
}
// is the grid full?
if (full == -1L)
// yes it is!
else
// no it isn't
Run Code Online (Sandbox Code Playgroud)