一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

asp.net数组随机排序三种实现方法

时间:2011-11-26 编辑:简简单单 来源:一聚教程网

通常4个人排是这样,以a为例,每一天上一个中班,每二天上一个早班和一个晚班,每三天休息,每四天继续上中班。这样就是三个人在轮班,多出的一个人在休月假,二个轮次后休假的人代替其中一人值班。
    以下是一个随机排班的算法,仅供参考。
            //按顺序排班,y代表日期,x代表班次 
        

 代码如下 复制代码

    string str = new string { "张","王","赵","李"};
            int b = 0;

            string  abc=new string;
            for(int y=0;y<30;y++)
            {
                for (int x = 0; x < 3; x++)
                {
                    abc = str;
                    b++;
                }
            }

            //以下随机排序可保证每个人的值班次数不变
            Random ran = new Random();
            string temp;
            int x1, y1, x2, y2;
            for (int x = 0; x < 100; x++)
            {
                x1 = ran.Next(2);
                x2 = ran.Next(2);
                y1 = ran.Next(29);
                y2 = ran.Next(29);
                temp = abc;
                abc = abc;
                abc = temp;
            }

实例二

每次查询出来那个数组  ,数组里面数据的顺序都不一样

 代码如下 复制代码
int[] array = new int[10];
            for (int i = 0; i < 10; i++)
            {
                array[i] = i + 1;
            }
            int len = array.Length;
            Random rnd = new Random();
            for (int j = 0; j < len; j++)
            {
                int pos = rnd.Next(len);
                int temp = array[pos];
                array[pos] = array[j];
                array[j] = temp;
            }
            string sortStr = "";
            for (int i = 0; i < len;i++)
            {
                sortStr += array[i] + ",";
            }
            MessageBox.Show(sortStr);

数组的随机排序,也就是把一个数组的元素顺序打乱,例如洗牌。

 

 代码如下 复制代码

public static T[] RandomSort(T[] array)
        ...{
            int len = array.Length;
            List list = new List();
            T[] ret=new T[len];
            Random rand = new Random();
            int i = 0;
            while (list.Count < len)
            ...{
                int iter = rand.Next(0, len);
                if (!list.Contains(iter))
                ...{
                    list.Add(iter);
                    ret[i] = array[iter];
                    i++;
                }
               
            }
            return ret;
        }

调用例:
static void Main()
        ...{
            string [] aaa =...{ "3", "1", "7", "5", "4", "2", "6" };
            string [] bbb =RandomSort(aaa);
            for (int i = 0; i < 7; i++) Console.WriteLine(bbb[i]);
            Console.ReadLine();
}

热门栏目