dimanche 18 octobre 2015

Generating 8-bit unique random number

Is there any better way to generate 8-bit unique and random number in constant time ?

Below implementation returns 8-bit unique random number, but complexity is O(n=256) as it has to loop through the is_generated[] array till it generates one which has not been previously generated. Also it needs extra space for is_generated.

uint8_t
random_octate(void)
{   
    static bool     is_generated[256] = {false};
    uint32_t        num = rand()%256;

    while(is_generated[num])
    {
        num = rand() % 256;
    }

    is_generated[num] = true;
    return num;
}




Aucun commentaire:

Enregistrer un commentaire