lundi 9 mars 2020

generate array with random values (C)

So i wanted to have a function that takes an array and fills it with random integers. I'm guesing that's two argument, a pointer and the size of the array. I'd also be nice if i could choose if each number could reoccur or be unique (so another argument?). Lastly i'd like to control where the random numbers start. For example if i have an 100 cell array and lower bound set to 0 i want the range of random generation to be 0-100. If i have a 200 cell array and lower bound set to 300, i want it the range to be 300-500.

So i've come up with a function that looks good on paper but doens't work.

void generateRandomArray(unsigned int array[], unsigned int size, bool unique, unsigned int lowerBound)
{
    unsigned int i;
    srand(time(NULL));
    if(lowerBound + size > RAND_MAX)
    {
        exit(1);
    }
    if(unique)
    {
        bool index[size];
        unsigned int gen;
        for(i = 0; i < size; i++)
        {
            index[i] = false;
        }
        i = 0;
        while(!isTrue(index, size))
        {
            gen = (rand() % size + 1) + lowerBound;
            if(!index[gen - lowerBound - 1])
            {
                index[gen - lowerBound - 1] = true;
                array[i] = gen;
                i++;
            }
        }
    }
    else
    {
        for(i = 0; i < size; i++)
        {
            array[i] = (rand() % size + 1) + lowerBound;
        }
    }
    return;
}

bool isTrue(bool array[], unsigned int size)
{
    bool flag = true;
    int i;
    for(i = 0; i < size; i++)
    {
        if(!array[i])
        {
            flag = false;
        }
    }
    return flag;
}

I know it not particularly efficient, but what bothers me most is that it doesn't work. What happens is as soon as the function is called from main, program crashes with some big exit code. It seems that problems arise within the first part of the is unique if. What's causing it?




Aucun commentaire:

Enregistrer un commentaire