3

Possible Duplicate:
Is using Random and OrderBy a good shuffle algorithm?

Given an integer array of n consecutive number from 0, i.e.

0,1,2,..n

I wish to randomly generate a permutation of number,

say given

0,1,2,3

a possible one is 3,1,2,0

How to achieve it easily?

Community
  • 1
  • 1
william007
  • 17,375
  • 25
  • 118
  • 194

2 Answers2

11

first create an integer array of desired size and populate it with increasing consecutive numbers;

int n = 10;
int[] array = new int[n + 1];
for (int i = 0; i <= n; i++)
{
    array[i] = i;
}
Shuffle(array);

you can use Knuth / Fisher–Yates shuffle

/// <summary>
/// Knuth shuffle
/// </summary>        
public void Shuffle(int[] array)
{
    Random random = new Random();
    int n = array.Count();
    while (n > 1)
    {
        n--;
        int i = random.Next(n + 1);
        int temp = array[i];
        array[i] = array[n];
        array[n] = temp;
    }
}
daryal
  • 14,643
  • 4
  • 38
  • 54
9

Here is a easy way to do it with LINQ and a random generator.

int[] numbers = new int[] { 1,2,3,4,5,6,7,8,9 };

Random rnd = new Random();
int[] MyRandomNumbers = numbers.OrderBy(x => rnd.Next()).ToArray();

Reference: Best way to randomize an array with .NET

Community
  • 1
  • 1
fito
  • 129
  • 6
  • 3
    This is not an exact random permutation since there is a small probability for rnd.Next() to return the same number. When this happens you pick the first element. This means that the probability of the first element to be first is slightly larger than real random permutation.. – YaronZ Feb 23 '15 at 13:10
  • Doesn't this apply to any random algorithm? It's part of being random that a chance of staying the same exists. In my case, I worted ~450k entries and the result is permutated randomly in around 150ms. This is way quicker than every other algorithm I tried and it works every time (so far). – ecth Mar 22 '20 at 07:16
  • 1
    ecth: Number 1 will be before number 2 if its roll is less OR SAME as number 2's. If rnd.Next() returned only 0 or 1, then 1 will be before 2 in 3/4 cases. If rnd.Next() returns between minInt and maxInt, then the chance is close to 1/2, but slightly more. – Ferazhu Sep 18 '21 at 18:08