jeudi 30 juillet 2020

How to limit the occurrence of a randomly generated item in C++? [closed]

Suppose, an array can hold 10 elements and I want it to fill it with random integers ranging from 1 to 5. In C++, it can be easily done by using rand().

But I want to limit the number of occurrences of the digit 5 to a maximum of 2 times. [ At the end, the array must contain two 5s. ]

So, is there any function in C++ to set this constraint?

This is what I've done so far.

for(int i=0; i<10; i++)
{   num=rand()%5+1;
    if(num==5)
    {   if(count<2)
        {   count++;
            arr[i]=num;
        }
        else
        {   i--;
            continue;
        }
    }
    else
        arr[i]=num;
}

If you have any ideas, feel free to share it with me. Thanks.




Aucun commentaire:

Enregistrer un commentaire