码迷,mamicode.com
首页 > 其他好文 > 详细

利用random生成一组随机且不重复的随机数字

时间:2015-06-19 08:58:31      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        public static int Chaos_GetRandomSeed()
        {
            byte[] bytes = new byte[4];
            System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
            rng.GetBytes(bytes);
            return BitConverter.ToInt32(bytes, 0);
        }
        public static int[] hash(int i, int max)//生成随机函数,i数组的长度,max表示table长度,返回一个随机数组
        {
            int[] a = new int[i];
            for (int j = 0; j < i; j++)
            {
                Random ran = new Random(Chaos_GetRandomSeed());
                int k = ran.Next(0, max);
                a[j] = k;
                Console.Write(k+" ");
            }
            return a;
        }
        static void Main(string[] args)
        {
            hash(10, 3000);
            Console.ReadKey();
        }
    }
}

利用RNGCryptoServiceProvider()生成随机的种子,从而产生一组不相同的随机数。但是还是不能保证数组中不出现重复数字。
因此还需要改进,结果如下:

技术分享

我们可以使用两种方式初始化一个随机数发生器:

第一种方法不指定随机种子,系统自动选取当前时间作为随机种子:

Random ro = new Random();

第二种方法可以指定一个int型参数作为随机种子:

 做出修改后的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        public static int Chaos_GetRandomSeed()
        {
            byte[] bytes = new byte[4];
            System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
            rng.GetBytes(bytes);
            return BitConverter.ToInt32(bytes, 0);
        }
        public static int[] hash(int i, int max)//生成随机函数,i数组的长度,max表示table长度,返回一个随机数组
        {
            int[] a = new int[i];
            for (int j = 0; j < i; j++)
            {
                bool flag = false;
                Random ran = new Random(Chaos_GetRandomSeed());
                int k = ran.Next(0, max);
                foreach(int t in a)//判断是否已经存在相等的数字,若存在flag置为true
                {
                    if(t==k)
                    {
                        flag = true;
                    }
                }
                if (flag)
                {
                    j--;
                }
                else
                {
                    a[j] = k;
                }
                Console.Write(k+" ");
            }
            return a;
        }
        static void Main(string[] args)
        {
            hash(10, 3000);
            Console.ReadKey();
        }
    }
}

结果显示无误。

利用random生成一组随机且不重复的随机数字

标签:

原文地址:http://www.cnblogs.com/xz-blogs/p/4587600.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!