Skiplast随机函数需要解释

时间:2010-10-01 05:24:05

标签: c++ data-structures

我在C ++中阅读了有关skipList实现的内容,我不理解这个随机函数:

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;
} 

感谢阅读,我在等你的回答:)

2 个答案:

答案 0 :(得分:3)

因此,跳过列表的工作方式是使新节点在级别上链接到其他节点,随机选择是否添加级别。通常,这意味着为新节点要链接的每个级别翻转一次硬币。如果它出现在头部,你会上升一个水平并再次翻转,如果是尾巴,你就完成了。

它的作用是模拟硬币翻转几次,但只调用一次随机数源,并应用具有相同概率分布的函数作为连续硬币翻转的总和

答案 1 :(得分:2)

  // 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
}