Skiplast random function need explained

167 views Asked by At

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

There are 2 answers

0
SingleNegationElimination On BEST ANSWER

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

2
Alexander Rafferty On
  // 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
}