Link to home
Start Free TrialLog in
Avatar of Q-M
Q-MFlag for Canada

asked on

Speeding up Random number list generator

Hi there,

I want to speed up my random number list generator because I've noticed that it is running really slow once I try to generate a list of over 20000 numbers. They all have to be unique and in random order.

So far, my code seems to work pretty fast with about 10000 numbers, but anything higher and it takes a bit too long to process.

I'm wondering if there is another way to speed up this process.

Attached is my code that I have.
private List<int> OutputRandomNumbers(int maxNumber)
{
    lblTextOutput.Text = "";
    List<int> numbers = new List<int>(maxNumber);

    //Add each number to the list
    for(int i = 1; i <= maxNumber; i++){ numbers.Add(i); }

    //Re-Order the list of numbers
    Random rand = new Random();
    int index = numbers.Count;
    while(index > 0)
    {
        index--;
        int randomIndex = rand.Next(1, numbers.Count);
        int tempVal = numbers[randomIndex];
        numbers[randomIndex] = numbers[index];
        numbers[index] = tempVal;
        lblTextOutput.Text += tempVal + (index > 1 ? ", " : "");
    }
    return numbers;
}

Open in new window

SOLUTION
Avatar of EDDYKT
EDDYKT
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Q-M

ASKER

Thanks guys, I used String.Join and worked great. Runs instantly.