zoukankan      html  css  js  c++  java
  • 生成不重复的随机数

    最近项目中用到大量的不重复的随机数,

    在网上查了资料http://blog.csdn.net/xujinpeng99/article/details/6387782

    Random类都是伪随机的,就是看上去象随机但实际上是用一个公式推导出来的,只要能产 生足够长的伪随机序列就行。相同的种子生成的随机系列肯定相同,

    所以一般找个随即的数 做种子这样产生的随机系列可以保证每次都不同,默认是根据计算机时钟精度来设置seed种子.

    Random rand = new Random(Guid.NewGuid().GetHashCode());

    MSDN上关于GUID的解释:
    GUID 是一个 128 位整数(16 字节),可用于所有需要唯一标识符的计算机和网络。此标
    识符重复的可能性非常小。

    ///<summary>   
        ///产生不重复随机数的应用    
        ///摘要 C#随机数的应用中 如果是需要在短时间内产生大量随机数 推荐使用Guid.NewGuid().GetHashCode()作为种子    
        ///</summary>   
        class Program
        {
            static void Main(string[] args)
            {
                FileStream fs = new FileStream(@"c:\Code.txt", FileMode.Create, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs);
                List<int> Numbers = Program.GetRandom(1000000000,2147483640,210);
                for (int i = 0; i < Numbers.Count; i++)
                {
                    Console.WriteLine("GC212" + Numbers[i]);
                    sw.WriteLine("GC212" + Numbers[i]);
                }
                sw.Close();
                Console.WriteLine("写入文件完成");
                Console.ReadLine();
            }
    
            ///<summary>   
            ///返回一组唯一不重复的随机数   
            ///</summary>   
            ///<param name="minValue">最小值</param>   
            ///<param name="maxValue">最大值</param>   
            ///<returns>返回一组唯一不重复的随机数</returns>   
            public static List<int> GetRandom(int minValue, int maxValue, int count)
            {
                List<int> Numbers = new List<int>();
                //使用Guid.NewGuid().GetHashCode()作为种子,可以确保Random在极短时间产生的随机数尽可能做到不重复   
                Random rand = new Random(123456);
                Console.WriteLine("GUID:" + Guid.NewGuid().GetHashCode());
                int item;
                for (int i = minValue; i <= maxValue; i++)
                {
                    item = rand.Next(minValue, maxValue + 1);
                    while (Numbers.IndexOf(item) != -1)
                    {
                        item = rand.Next(minValue, maxValue + 1);
                    }
                    Numbers.Add(item);
                    if (Numbers.Count >= count)
                        break;
    
                }
    
                return Numbers;
            }
        }
  • 相关阅读:
    CF 336494 C. Meme Problem
    MySql备份
    MySQL索引背后的数据结构及算法原理
    show profile 开启权限
    示例数据库
    索引使用策略及优化
    shiro权限登录案例
    Swagger技术
    Shiro框架
    shiro授权管理
  • 原文地址:https://www.cnblogs.com/youmeng/p/2825644.html
Copyright © 2011-2022 走看看