- 最后登录
- 2019-12-2
- 注册时间
- 2012-8-25
- 阅读权限
- 90
- 积分
- 34660
  
- 纳金币
- 38279
- 精华
- 111
|
大家都知道,很多时候我们在做项目的过程中都会用到随机算法,需要生成一些随机数。但如果利用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;
- }
复制代码 |
|