Shuffle ICollection - CSharp System.Collections

CSharp examples for System.Collections:ICollection

Description

Shuffle ICollection

Demo Code


using System.Security.Cryptography;
using System.Collections;
using System;// w ww. j  a  v a  2  s.c om

public class Main{
        public static ICollection Shuffle(ICollection c) {
         if (c == null || c.Count <= 1) {
            return c;
         }

         byte[] bytes = new byte[4];
         RNGCryptoServiceProvider cRandom = new RNGCryptoServiceProvider();
         cRandom.GetBytes(bytes);

         int seed = BitConverter.ToInt32(bytes, 0);
         Random random = new Random(seed);

         ArrayList orig = new ArrayList(c);
         ArrayList randomized = new ArrayList(c.Count);
         for (int i = 0; i < c.Count; i++) {
            int index = random.Next(orig.Count);
            randomized.Add(orig[index]);
            orig.RemoveAt(index);
         }
         return randomized;
      }
}

Related Tutorials