标签:
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(); } } }
结果显示无误。
标签:
原文地址:http://www.cnblogs.com/xz-blogs/p/4587600.html