08-26-2016, 03:20 PM
(This post was last modified: 08-26-2016, 03:21 PM by Soldier . . ..)
It is based on a Multiply With Carry generator and I added a extra, which makes the chance that the value is the same as the previous one, a lot smaller.
Do note that the constant and (sometimes) the start numbers can make or brake the randomness!
The variable iSize is the max value - 1 it can select from.
So if iSize = 16, the return value will be between 0 and 15.
Made a little change: If both variable "m_z" and "m_w" become 0 at the same time. The output will always be 0. (something that we don't want )
note:
The variable "m_z", "m_w" and "iRandOld" need to be saved in a way that they wont get cleared.
(in 'c/c++' static enables you to save the declared variable outside the function)
Do note that the constant and (sometimes) the start numbers can make or brake the randomness!
The variable iSize is the max value - 1 it can select from.
So if iSize = 16, the return value will be between 0 and 15.
Made a little change: If both variable "m_z" and "m_w" become 0 at the same time. The output will always be 0. (something that we don't want )
Code:
unsigned int random (unsigned int iSize)
{
static unsigned int m_z = 12434;
static unsigned int m_w = 33254;
static unsigned int iRandOld = 0;
m_z = 36969 * (m_z & 65535) + (m_z >> 16);
m_w = 18000 * (m_w & 65535) + (m_w >> 16);
if (iRandOld == (((m_z << 16) + m_w) % iSize))
{
m_z = 36969 * (m_z & 65535) + (m_z >> 16);
m_w = 18000 * (m_w & 65535) + (m_w >> 16);
}
if ((m_z == 0) && (m_w == 0))
{m_z = 12434;}
iRandOld = ((m_z << 16) + m_w) % iSize;
return (iRandOld);
}
note:
The variable "m_z", "m_w" and "iRandOld" need to be saved in a way that they wont get cleared.
(in 'c/c++' static enables you to save the declared variable outside the function)