Search code examples
c#arrayslistrandomdiscord

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.


Solution

  • Here is a solution, that shuffles the values and returns each value until the list is exhausted, then starts all over:

    int[] GenerateNewArray(int n)
    {
        // Define an array of values we wish to return and populate it
        int[] baseValues = Enumerable.Range(1, n).ToArray();
        Random rnd=new Random();
        // Shuffle the array randomly using Linq
        return baseValues.OrderBy(x => rnd.Next()).ToArray(); 
    }
    
    void Main()
    {
        int nNumbers = 10;
        while (true)
        {
            // Generate a new randomized array
            var values = GenerateNewArray(nNumbers);
            // Print each value 
            for (int i=0;i<nNumbers;i++)
            {
                Console.WriteLine($"The number generated is {values[i]}");
            }
        }
    }
    

    EDIT Parameterized the number of unique values.