Randomly permutation of n consecutive integer number
algorithm, c#
Solution
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;
}
}
Problem
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?