Re: Random number generator
Re: Random number generator
How large is the range of numbers you are generating? If the range of numbers you are generating are small to medium, maybe a bit array as boolean flags denoting if a number has been generated already?
I didn't compile this, I just typed it in.
Code:
// Our range of numbers is say 0 to and including 1023, so we have
// 1024 possible numbers, divide by 8 and we need 128 bytes for
// out bit array
struct BitArray
{
inline BitArray()
{
for (unsigned long i = 0; i < 128; ++i)
{
Flags[i] = 0;
}
}
unsigned char Flags[128];
inline bool IsBitSet(unsigned long dwValue)
{
if (dwValue < 1024)
{
const unsigned long dwByteIndex = dwValue / 8; // dwValue >> 3;
const unsigned long dwBitIndex = dwValue % 8; // dwValue & 7;
const unsigned char ucBit = 1 << dwBitIndex;
return (Flags[dwByteIndex] & ucBit) != 0;
}
else
{
// throw an appropriate exception here
}
}
inline void SetBit(unsigned long dwValue,bool bValue)
{
if (dwValue < 1024)
{
const unsigned long dwByteIndex = dwValue / 8;
const unsigned long dwBitIndex = dwValue % 8;
const unsigned char ucBit = 1 << dwBitIndex;
if (bValue == true)
{
Flags[dwByteIndex] |= ucBit;
}
else
{
Flags[dwByteIndex] &= ~ucBit;
}
}
else
{
// throw an appropriate exception here
}
}
};
int main(int argc,char * argv[])
{
srand(::GetTickCount()); // Probably should use CRT function, but whatever...
int Spots[1024];
int nCount = 0;
BitArray myFlags;
while (nCount < 1024)
{
const int nTemp = rand() % 1024; // rand() & 1023; // NOTE: Because of power of 2 could use AND
// check if the bit is set
if (myFlags.IsBitSet(nTemp) == true)
{
continue;
}
else
{
Spots[nCount] = nTemp;
myFlags.SetBit(nTemp,true);
++nCount;
}
}
// whatever you need from here
return 0;
}
Re: Random number generator
^If you're going to take that approach, a std::bitset or a std::vector<bool> (which is not a true vector, and should be replaced by boost::dynamic_bitset if you have access to Boost) is simpler than rolling a new class.
I agree that std::random_shuffle will probably be good enough though.