mercredi 15 juin 2022

srand() and rand() giving the same numbers in c [duplicate]

I have this code

BTree randomTreeRec(int n)
{
    if(n <= 0)
        return NULL;
    //random value
    srand(time(NULL));
    int *value = malloc(sizeof(int));
    *value = rand() % 101;

    BTree bt = buildTree(NULL, NULL, value);

    //branches option 0 is left 1 is right

    int branches = rand() % 2;

    if(branches == 0)
        bt->left = randomTree(n - 1);
    if(branches == 1)
        bt->right = randomTree(n - 1);
    return bt;
}

why does rand always give me the same numbers even if I'm using srand(time(NULL)) ? I tried putting srand out from the recursive function because I thought the cpu was too fast and always used the same seed but it didn't work

BTree randomTreeRec(int n)
{
    if(n <= 0)
        return NULL;

    //random value
    int *value = malloc(sizeof(int));
    *value = rand() % 101;

    BTree bt = buildTree(NULL, NULL, value);

    //branches 0 is left 1 is right
    int branches = rand() % 2;
    if(branches == 0)
        bt->left = randomTree(n - 1);
    if(branches == 1)
        bt->right = randomTree(n - 1);
    return bt;
}

BTree randomTree(int n)
{
    srand(time(NULL));
    return randomTreeRec(n);
}

how can I solve this?




Aucun commentaire:

Enregistrer un commentaire