Kato_Yang wrote...
Very nice indeed. I'm studying the binary arithmetic and bitwise operators so this is instructive to me, thank you both.
Kato
Looking again at the script there is one critical flaw. For single bit numbers the average number of times the function will be called is 32. The maximum times NWScript allows for such self-referencing is 125. There is a 1.8% chance that single bit numbers would cause an overflow number of loopings. There are two ways around this. Either 1. decrease MAX_BITS to something like 16, or 2. store the usable bits as local Integers, and return a random local integer.
Below is a script demonstrating method 2.
int RandomBit(int nInteger)
{
if(!nInteger) return FALSE;// If there are no good bits none can be returned
int nBitValue = 1;
int nCount = 0;
while(nBitValue <= nInteger && nBitValue != 0) // Stores all good bits in one loop
{
if(nBitValue & nInteger)
{
nCount++;
SetLocalInt(OBJECT_SELF, "BIT" + IntToString(nCount), nBitValue);
}
nBitValue << 1;
}
int nReturn = GetLocalInt(OBJECT_SELF, "BIT" + IntToString(Random(nCount) + 1)); //Get a random stored bit
while(nCount > 0)// Clean up
{
DeleteLocalInt(OBJECT_SELF, "BIT" + IntToString(nCount));
nCount--;
}
return nReturn;
}
EDIT: Fixed an off by one issue for nCount
Modifié par WhiZard, 11 novembre 2011 - 05:00 .