mercredi 16 mars 2022

Constantly generating unique and random values in a specific range in C#

I am implementing this code in my discord bot, where I want to be able to generate unique numbers from 1 to 10 (as suggested above) whenever I input a single command.

Turns out that the values sometimes are repeated. Therefore I was suggested to add an array (used[ ]) and a loop in order to check every time if the value has been generated already.

Random random = new Random();
    int[] used = new int[10];
    int rng = 0;
    while (!used.Contains(rng))
    {
        rng = random.Next(1, 10);
    }

    /* 
    I wish to store the generated value "rng" to the "used" array.
    e.g.
    used[0] = rng
    used[1] = rng
    used[2] = rng
    etc.
    */
    Console.WriteLine("The number generated is " + Convert.ToString(rng));

However, I don't know how to constantly add values to an array in an arranged order. (as seen by the commentations above)

In a more simple way, For 10 times I want the system to generate a number, and those numbers are randomly picked out of [1,10] and only once. If all the numbers have been generated once, all are free to be generated again.

Sorry for my bad interpretation. I have refined it with the comments that everyone has contributed.




Aucun commentaire:

Enregistrer un commentaire