Search code examples
c#randomgenerator

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;
    }

Solution

  • This is what my version would like like. Very similar to your final version but more compact and tests only one condition each time through the loop.

    public static Stack<int> RandomNumberGenerator(int lower, int upper, int count)
    {
        Random rnd = new();
        HashSet<int> set = new();
    
        while (set.Count < count)
            set.Add(rnd.Next(lower, upper + 1));
    
        return new Stack<int>(set);
    }