检查是否已使用特定索引 - 按位?
Check whether an specific index has been already used - Bitwise?
我想说,我感谢对以下问题的每一个贡献;
我目前正在编写一个数组洗牌器,它在不更改实例的情况下将数组的元素洗牌到不同的随机位置,因此不需要使用返回的创建的数组实例(该洗牌的调用)来重新评估数组字段。作为实验,我想创建一种替代其他现有洗牌算法(如 Fisher-Yates 洗牌算法)的方法。所以我尝试了几种操作,但我想我被卡住了。我可以创建一个数组来存储已使用的索引,并创建一个尚未使用的随机索引(在数组中我想要洗牌的每个元素的迭代过程中)。但我想让这种方式更清洁。因为按位运算可以帮助我,但只能使用 2^x 十六进制。
这是我想要实现的目标以及我已经尝试过但已简化的示例:
//Integer that holds information on what indices are being used
int used = 0;
//Some indices being used
used |= 3;
used |= 4;
used |= 6;
//Check whether the 2, 4 are used
boolean isUsed2 = (used & 2) != 0; //=> false as 2 is not used?
boolean isUsed4 = (used & 4) != 0; //=> true as 4 is used?
所以基本上我不明白的是我如何创建一个整数,其中包含有关已使用和未使用哪些特定值的信息。所以判断索引2或者0或者8是否已经被使用
希望我的英语是可以理解的。
此致
您必须按索引和按位右移您的 bitMask,并使用 0x1。
public boolean getBitState(int bitIndex, int bitMask) {
return (bitMask >> bitIndex & 0x1) == 0x1;
}
真=1,假=0
设置一点...
// returns new bitmask value
public int setBitState(int bitIndex, boolean value, int bitMask) {
if (value) {
return bitMask |= (0x1 << bitIndex);
} else {
return bitMask &= ~(0x1 << bitIndex);
}
}
我想说,我感谢对以下问题的每一个贡献;
我目前正在编写一个数组洗牌器,它在不更改实例的情况下将数组的元素洗牌到不同的随机位置,因此不需要使用返回的创建的数组实例(该洗牌的调用)来重新评估数组字段。作为实验,我想创建一种替代其他现有洗牌算法(如 Fisher-Yates 洗牌算法)的方法。所以我尝试了几种操作,但我想我被卡住了。我可以创建一个数组来存储已使用的索引,并创建一个尚未使用的随机索引(在数组中我想要洗牌的每个元素的迭代过程中)。但我想让这种方式更清洁。因为按位运算可以帮助我,但只能使用 2^x 十六进制。
这是我想要实现的目标以及我已经尝试过但已简化的示例:
//Integer that holds information on what indices are being used
int used = 0;
//Some indices being used
used |= 3;
used |= 4;
used |= 6;
//Check whether the 2, 4 are used
boolean isUsed2 = (used & 2) != 0; //=> false as 2 is not used?
boolean isUsed4 = (used & 4) != 0; //=> true as 4 is used?
所以基本上我不明白的是我如何创建一个整数,其中包含有关已使用和未使用哪些特定值的信息。所以判断索引2或者0或者8是否已经被使用
希望我的英语是可以理解的。
此致
您必须按索引和按位右移您的 bitMask,并使用 0x1。
public boolean getBitState(int bitIndex, int bitMask) {
return (bitMask >> bitIndex & 0x1) == 0x1;
}
真=1,假=0
设置一点...
// returns new bitmask value
public int setBitState(int bitIndex, boolean value, int bitMask) {
if (value) {
return bitMask |= (0x1 << bitIndex);
} else {
return bitMask &= ~(0x1 << bitIndex);
}
}