Shuffling a sequence of numbers in an array.

here this code will randomly shuffle consecutive series of numbers, from 1 up to 1000.

int[] theArray = new int[1000];

            int i = 0;
            while (i < theArray.Length)
            {
                theArray[i] = ++i;
            }


            // Work backward, swapping the last unswapped entry with any of the

            // remaining unswapped entries - including possibly itself.
            // This is really just slightly complicated way of doing a random 'draw',
            // which is exactly what is required to perform a shuffle.
            // Please note that the Random generator does not produce random numbers - it

            // produces a deterministic sequence of numbers with statistical properties similar

            // or at best equivalent to random numbers. For 'real' randomness, please turn

            // to System.Security.Cryptography.RNGCryptoServiceProvider.
            Random r = new Random();
            while (i > 1)
            {
                int j = r.Next(i);
                int t = theArray[--i];
                theArray[i] = theArray[j];
                theArray[j] = t;
            }


            for (i = 0; i < theArray.Length; ++i)
            {
                Response.Write(" "+theArray[i].ToString());
            }
        }


**************************************

copied from: http://forums.asp.net/t/1262293.aspx/2/10
 

Comments

Popular posts from this blog

c# console applicaton progress bar with spinner

Paging, sorting and searching in mvc + razor

C# SELF DESTRUCT CONSOLE APP