Shuffle IList In Place - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IList

Description

Shuffle IList In Place

Demo Code


using System.Linq;
using System.Text;
using System.Globalization;
using System.ComponentModel;
using System.Collections.Generic;
using System.Collections;

public class Main{
        public static void ShuffleInPlace<T>(this IList<T> items, int times)
        {//from w w w  .j  av a2 s  .com
            for (int j = 0; j < times; j++)
            {
                var rnd = new Random((int)(DateTime.Now.Ticks % int.MaxValue) - j);

                for (int i = 0; i < items.Count; i++)
                {
                    var index = rnd.Next(items.Count - 1);
                    var temp = items[index];
                    items[index] = items[i];
                    items[i] = temp;
                }
            }
        }
        public static void ShuffleInPlace<T>(this IList<T> items)
        {
            ShuffleInPlace(items, 4);
        }
}

Related Tutorials