纳金网
标题:
利用C#生成随机不重复的随机数(带排序)
[打印本页]
作者:
狂风大尉
时间:
2014-6-28 01:52
标题:
利用C#生成随机不重复的随机数(带排序)
大家都知道,很多时候我们在做项目的过程中都会用到随机算法,需要生成一些随机数。但如果利用C#本身或者
unity
自身带的random方法来生成随机数的话,都会有重复的现象。前段时间特别研究了一下如何生成不重复的随机数,现在分享给大家,希望能对大家有用。大家如果有更好的随机不重复算法,也可以再评论下大家共同讨论下。
下面是源码:
public static int[] getRandoms(int sum, int max)
{
int[] arr = new int[sum];
int j = 0;
//表示键和值对的集合。
Hashtable hashtable = new Hashtable();
System.Random rm = new System.Random();
for (int i = 0; hashtable.Count < sum; i++)
{
//返回一个小于所指定最大值的非负随机数
int nValue = rm.Next(max);
//containsValue(object value) 是否包含特定值
if (!hashtable.ContainsValue(nValue) && nValue != 0)
{
//把键和值添加到hashtable
hashtable.Add(nValue, nValue);
//Debug.Log(i);
arr[j] = nValue;
j++;
}
}
int temp;
//最多做n-1趟排序
for (int i = 0; i < arr.Length - 1; i++)
{
//对当前无序区间score[0......length-i-1]进行排序(j的范围很关键,这个范围是在逐步缩小的)
for (j = 0; j < arr.Length - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return arr;
}
复制代码
作者:
hyui
时间:
2014-6-28 02:22
Good to know !
作者:
hxsdsjr
时间:
2014-7-29 20:46
好东东大家支持啊
欢迎光临 纳金网 (http://go.narkii.com/club/)
Powered by Discuz! X2.5