mercredi 21 septembre 2022

create stack with unique random numbers fast

I created a method where I generate a stack of random unique numbers. The code works but I need this to run a lot faster. Does anyone have a suggestion.

Lower is the lowest number for the random number, upper is the highest number for the random number and count is the amount of numbers I need.

I tried searching around for a better solution, but I couldn't make it work.

public static Stack<int> RandomNumbersGenerator(int lower, int upper, int count)
        {
            Stack<int> stack = new Stack<int>();
            Random rnd = new Random();
            while (count > 0)
            {
                int h = rnd.Next(lower, (upper + 1));
                if (!stack.Contains(h))
                {
                    stack.Push(h);
                    count--;
                }

            }
            return stack;
        }



Aucun commentaire:

Enregistrer un commentaire