产生随机数

public const int Num = 50000;         //数目
public const int MaxValue = 880296;   //最大数
public const int MinValue = 1;    //最小数


#region  产生随机数部分
        /// <summary>
        /// 随机数进行排序
        /// </summary>
        public int[] sort(int[] num)
        {
            int i, j, temp;
            int n = num.Length;
            for (i = 0; i < n - 1; i++)
            {
                for (j = i + 1; j < n; j++) /*注意循环的上下限*/
                {
                    if (num[i] > num[j])
                    {
                        temp = num[i];
                        num[i] = num[j];
                        num[j] = temp;
                    }
                }
            }
            return num;
        }
        /// <summary>
        /// 判断随机数是否重复
        /// </summary>
        public int getNum(int[] arrNum, int tmp, int minValue, int maxValue, Random ra)
        {
            int n = 0;
            while (n <= arrNum.Length - 1)
            {
                if (arrNum[n] == tmp) //利用循环判断是否有重复
                {
                    tmp = ra.Next(minValue, maxValue); //重新随机获取。
                    getNum(arrNum, tmp, minValue, maxValue, ra);//递归:如果取出来的数字和已取得的数字有重复就重新随机获取。
                }
                n++;
            }
            return tmp;
        }
        /// <summary>
        /// 获取随机数
        /// </summary>
        public Collection<long> getRandomNum(int num, int minValue, int maxValue)
        {
            Random ra = new Random(unchecked((int)DateTime.Now.Ticks));
            Collection<long> strNum = new Collection<long>();
            int[] arrNum = new int[num];
            int tmp = 0;

            for (int i = 0; i <= num - 1; i++)
            {
                tmp = ra.Next(minValue, maxValue); //随机取数
                Console.WriteLine("排序前的:" + tmp);
                arrNum[i] = getNum(arrNum, tmp, minValue, maxValue, ra); //取出值赋到数组中
            }

            this.sort(arrNum);
            string RandomNum = "RandomNum.txt";
            for (int i = 0; i < arrNum.Length; i++)
            {
                string s = Convert.ToString(arrNum[i]);
                Console.WriteLine("排序后的:" + s);
                using (FileStream fst1 = new FileStream(RandomNum, FileMode.Append))
                {
                    using (System.IO.StreamWriter _writer1 = new System.IO.StreamWriter(fst1))
                    {
                        _writer1.WriteLine("RowId = " + s);
                        _writer1.Close();
                        fst1.Close();
                    }
                }
                strNum.Add(Convert.ToInt64(s));
            }
            return strNum;
        }
        #endregion


  //调用中……

  ParserStatuteByLawCase RandomStatuteId = new ParserStatuteByLawCase();
   RandomStatuteId.getRandomNum(10000, 0, 700000);
posted @ 2011-05-11 13:24  石 磊  阅读(447)  评论(0编辑  收藏  举报