生成100个不重复的随机数算法

时间:2022-10-20 09:50:15

从1~1000中生成不重复的随机数100个,用到了hashtable,这样的话减少检索重复数的范围,这个也是面试时经常问到的一个题目。

代码如下:

 Int32 count = 0;
            Dictionary<Int32,IList<Int32>> results=new Dictionary<int,IList<int>>();
            while (count < 100)
            {
                while (true)
                {
                    Int32 rand = new Random().Next(1, 1000);
                    Int32 mod = rand % 10;
                    if (results.Keys.Contains(mod))
                    {
                        if (!results[mod].Contains(rand))
                        {
                            results[mod].Add(rand);
                            count++;
                            break;
                        }
                    }
                    else
                    {
                        IList<Int32> lists = new List<Int32>();
                        lists.Add(rand);
                        results.Add(mod, lists);
                        count++;
                        break;
                    }
                }
            }
            //output
            foreach (Int32 k in results.Keys)
            {
                foreach (Int32 v in results[k])
                {
                    Response.Write(v.ToString()+"  ");
                }
            }
            Response.Write("<br/>"+count.ToString());
            Response.Flush();
            Response.End();