Shuffle elements in very good random order. - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IEnumerable

Description

Shuffle elements in very good random order.

Demo Code


using System.Security.Cryptography;
using System.Linq;
using System.Collections.Generic;
using System;//from   w w  w . j  a v a  2s . com

public class Main{
        /// <summary>
        /// Shuffle elements in very good random order. Very slow method. To get a random on the order used RNGCryptoServiceProvider
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source)
        {
            var list = source.ToList();
            list.ShuffleThis();
            return list;
        }
        /// <summary>
        /// Shuffle elements of list in very good random order. Very slow method. To get a random on the order used RNGCryptoServiceProvider
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        public static void ShuffleThis<T>(this IList<T> list)
        {
            var provider = new RNGCryptoServiceProvider();
            var n = list.Count;
            while (n > 1)
            {
                var box = new byte[1];
                do
                {
                    provider.GetBytes(box);
                }
                while (!(box[0] < n * (Byte.MaxValue / n)));
                var k = (box[0] % n);

                n--;

                var value = list[k];
                list[k] = list[n];
                list[n] = value;
            }
        }
}

Related Tutorials