随机排序

原来取随机不重复数的时候是这么写的

            int[] arr = new int[5];
            Random ran = new Random();
            for (int i = 0; i < arr.Length; )
            {
                int item = ran.Next(0,20);
                if (!arr.Contains(item))
                {
                    arr[i] = item;
                    i++;
                }
            }

            foreach (var a in arr)
            {
                Console.WriteLine(a);
            }

这样能得到不重复的随机数组

但在应用中发现,比如一个数组为{a,b,c,d,e},取索引值随机排序,random取值为0到4也就是Next(0,5)

一旦排到还剩下一个索引的时候比如还有4没有排进去,那么random还会不停的随机可能是,比如随机出来

1,2,3,0,2,3,4,这样1,2,3,0,2,3那些次都白费了,其实你知道只有一个4了

这样上面那个纯的随机数就白白耽误很多工夫,

所以后来写成这样

            List<string> list = new List<string>() { "a", "b", "c", "d", "e"};//目标数组
            List<int> indexList = new List<int>() { 0, 1, 2, 3, 4};//索引序列

            Random ran = new Random();

            for (int i = indexList.Count - 1; i >= 0; i--)
            {
                int index = ran.Next(0, indexList.Count);
                Console.WriteLine(list[indexList[index]]);//用随机数取索引值
                indexList.RemoveAt(index);//取完的索引出序列保证不重复
            }

先用一个list装进要用数组的所有索引,用随机数取索引数组的随机值,然后用List的RemoveAt函数删除已经调用过的索引,

这样就能保证不会像上面那样明明还剩下一个数,还要再多random好几次,但问题是看起来好像还是太麻烦,网上搜了搜

还有一种直接交换数组值的办法,看起来更简单些

            string[] strArray = "a,b,c,d,e".Split(',');
            Random ran = new Random();
            //随机交换数组内容,达到随机排序效果
            for (int i = 0; i < strArray.Length; i++)
            {
                int index = ran.Next(0, strArray.Length);
                string temp = strArray[i];
                strArray[i] = strArray[index];
                strArray[index] = temp;
            }

感觉这是一种通用点的方法,还有一种针对DataTable的方法,大概思路就是,在DataTable中添加一个顺序列比如叫sort

大概是这样

            DataTable dt = new DataTable();
            Random ran = new Random();
            dt.Columns.Add("sort",typeof(int));
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dt.Rows[i]["sort"] = ran.Next(0,100);
            }

            DataView dv = dt.AsDataView();
            dv.Sort = "sort asc";
            dt = dv.ToTable();

随机值和索引脱离开,也不怕重复。当然desc也行,如果觉得还不够随机,那可以吧next最大值写大点。

应该还有更好的方法,楼主脑残,只想到这么多

原文地址:https://www.cnblogs.com/stupidanimal/p/4993510.html