zoukankan      html  css  js  c++  java
  • 将一维数组中元素随机打乱排序

    从原List中每次随机取一项,添加到新的List中,并在原List中删除。这样重复,直到原List为空为止。

    public static List<T> GetRandomList<T>(List<T> inputList)
    {
        //Copy to a array
        T[] copyArray = new T[inputList.Count];
        inputList.CopyTo(copyArray);
    
        //Add range
        List<T> copyList = new List<T>();
        copyList.AddRange(copyArray);
    
        //Set outputList and random
        List<T> outputList = new List<T>();
        Random rd = new Random(DateTime.Now.Millisecond);
    
        while (copyList.Count > 0)
        {
            //Select an index and item
            int rdIndex = rd.Next(0, copyList.Count - 1);
            T remove = copyList[rdIndex];
    
            //remove it from copyList and add it to output
            copyList.Remove(remove);
            outputList.Add(remove);
        }
        return outputList;
    }
    用linq
    List<T> l = new List<T>();
    l = l.Select(a => new { a, newID = Guid.NewGuid() }).OrderBy(b => b.newID).Select(c=>c.a).ToList();

    得到随机数的方法

    Random r=new Random();

    int n1=r.Next();        //返回非负随机整数

    Response.Write(n1+"<br>");

    int n2=r.Next(10);   //返回一个小于所指定最大值(10)的非负随机整数

    Response.Write(n2+"<br>");

    int n3=r.Next()%10;  //返回一人小于所指定最大值(10)的非负随机整数

    Response.Write(n3+"<br>");

    int n4=r.Next(1,20);  //返回一个指定范围(1-20)内的随机整数

    Response.Write(n4+"<br>");

    double d5=r.NextDouble();  //得到一个介于0.0-1.0之间的随机整数

    Response.Write(d5+"<br>");

  • 相关阅读:
    Hello world
    Kubernetes容器云平台建设实践
    工作方法决定自己的发展
    Excel中对身份证号的处理
    详解慢查询日志的相关设置及mysqldumpslow工具
    安全测试工具简介
    Redis使用
    linux centos 查看防火墙firewalld、iptables状态
    悄悄地存在这里,因为里面的一句话
    GAE Python 2009322
  • 原文地址:https://www.cnblogs.com/shy1766IT/p/6229536.html
Copyright © 2011-2022 走看看