bloggerads

2016年1月1日 星期五

C# : shuffling a given array

Shuffling a given array in C#

static Random _random = new Random();

static void Shuffle<T>(T[] array)
{
    int n = array.Length;
    for (int i = 0; i < n; i++)
    {
        // NextDouble Returns a random floating-point number that is greater than or equal to 0.0, and less than 1.0.
        int r = i + (int)(_random.NextDouble() * (n - i)); 
        T t = array[r];
        array[r] = array[i];
        array[i] = t;
    }
}

static void Main(string[] args)
{
    int[] array = new int [] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    Shuffle(array);
    foreach (int value in array)
    {
        Console.WriteLine(value);
    }
}

沒有留言:

張貼留言