views:

41

answers:

2

I read about skipList implementation in C++ and I don't understand this random function :

float frand() {
    return (float) rand() / RAND_MAX;
}
int random_level() {
    static bool first = true;

    if (first) {
        srand( (unsigned)time(NULL) );
        first = false;
    }

    int lvl = (int)(log(frand())/log(1.-P));
    return lvl < MAX_LEVEL ? lvl : MAX_LEVEL;
} 

Thanks for reading and I'm waiting for your answer :)

+2  A: 
  // this function generates a random number between 0 and 1
float frand() {
    return (float) rand() / RAND_MAX;  // RAND_MAX is the biggest possible value returned by rand()
}
int random_level() {
    static bool first = true;   // a static variable to track whether or not this is the first run of the function

    if (first) {  // if this is the first time the function has been called...
        srand( (unsigned)time(NULL) );    // generate a seed from the current time
        first = false; // set first to false
    }

    int lvl = (int)(log(frand())/log(1.-P));  // generate the value of lvl with some weird log functions
    return lvl < MAX_LEVEL ? lvl : MAX_LEVEL;  // cap the value to MAX_LEVEL, and return
} 
Alexander Rafferty
I love the way you call "some weird log functions" but the that is the exactly what I need to know.
nXqd
I'm not a math genius, so I don't know exactly what it is trying to accomplish, but I think it is moving the distribution of the random numbers to one side.
Alexander Rafferty
+3  A: 

So, the way skiplists work is it makes the new node link to other nodes at levels, randomly choosing to add a level or not. Normally this means flipping a coin once for each level the new node is intended to link to. if it comes up heads, you go up a level and flip again, if tails, you're done.

What this does is it simulates the flipping of that coin several times, but only calling the random number source once, and applying a function with the same probability distribution as summing consecutive coin flips

TokenMacGuy