Beispiel #1
0
        public static T[,] Random <T>(this T[,] array)
        {
            if (array == null)
            {
                throw CommonExceptions.ArgumentNull("array");
            }
            Contract.Ensures(Contract.Result <T[, ]>() != null);
            int w   = array.GetLength(1);
            int idx = array.Length;

            for (int i = array.GetLength(0) - 1; i >= 0; i--)
            {
                for (int j = w - 1; j >= 0; j--)
                {
                    int r = RandomExt.Next(idx--);
                    int x = r % w;
                    int y = r / w;
                    if (y != i || x != j)
                    {
                        T temp = array[i, j];
                        array[i, j] = array[y, x];
                        array[y, x] = temp;
                    }
                }
            }
            return(array);
        }
Beispiel #2
0
 /// <summary>
 /// 将数组进行随机排序。
 /// </summary>
 /// <typeparam name="T">数组中元素的类型。</typeparam>
 /// <param name="array">要进行随机排序的数组。</param>
 /// <returns>已完成随机排序的数组。</returns>
 /// <remarks>应保证每个元素出现在每个位置的概率基本相同。
 /// 采用下面的代码进行测试:
 /// <code>int size = 10;
 /// int[] arr = new int[size];
 /// int[,] cnt = new int[size, size];
 /// for (int i = 0; i { 200; i++)
 /// {
 ///     arr.Fill(n => n).Random();
 ///     for (int j = 0; j { size; j++) cnt[j, arr[j]]++;
 /// }
 /// for (int i = 0; i { size; i++)
 /// {
 ///     for (int j = 0; j { size; j++)
 ///         Console.Write("{0} ", cnt[i, j]);
 ///     Console.WriteLine();
 /// }</code>
 /// </remarks>
 /// <overloads>
 /// <summary>
 /// 将数组进行随机排序。
 /// </summary>
 /// </overloads>
 public static T[] Random <T>(this T[] array)
 {
     if (array == null)
     {
         throw CommonExceptions.ArgumentNull("array");
     }
     Contract.Ensures(Contract.Result <T[]>() != null);
     for (int i = array.Length - 1; i > 0; i--)
     {
         int j = RandomExt.Next(i + 1);
         if (j != i)
         {
             T temp = array[i];
             array[i] = array[j];
             array[j] = temp;
         }
     }
     return(array);
 }