纳金网

标题: 利用C#生成随机不重复的随机数(带排序) [打印本页]

作者: 狂风大尉    时间: 2014-6-28 01:52
标题: 利用C#生成随机不重复的随机数(带排序)

大家都知道,很多时候我们在做项目的过程中都会用到随机算法,需要生成一些随机数。但如果利用C#本身或者unity自身带的random方法来生成随机数的话,都会有重复的现象。前段时间特别研究了一下如何生成不重复的随机数,现在分享给大家,希望能对大家有用。大家如果有更好的随机不重复算法,也可以再评论下大家共同讨论下。
      
    下面是源码:
  1. public static int[] getRandoms(int sum, int max)
  2.     {
  3.         int[] arr = new int[sum];
  4.         int j = 0;
  5.         //表示键和值对的集合。
  6.         Hashtable hashtable = new Hashtable();
  7.         System.Random rm = new System.Random();
  8.         for (int i = 0; hashtable.Count < sum; i++)
  9.         {
  10.             //返回一个小于所指定最大值的非负随机数
  11.             int nValue = rm.Next(max);
  12.             //containsValue(object value)   是否包含特定值
  13.             if (!hashtable.ContainsValue(nValue) && nValue != 0)
  14.             {
  15.                 //把键和值添加到hashtable
  16.                 hashtable.Add(nValue, nValue);
  17.                 //Debug.Log(i);
  18.                 arr[j] = nValue;

  19.                 j++;
  20.             }
  21.         }
  22.         int temp;
  23.         //最多做n-1趟排序
  24.         for (int i = 0; i < arr.Length - 1; i++)
  25.         {
  26.             //对当前无序区间score[0......length-i-1]进行排序(j的范围很关键,这个范围是在逐步缩小的)
  27.             for (j = 0; j < arr.Length - i - 1; j++)
  28.             {
  29.                 if (arr[j] > arr[j + 1])
  30.                 {
  31.                     temp = arr[j];
  32.                     arr[j] = arr[j + 1];
  33.                     arr[j + 1] = temp;
  34.                 }
  35.             }
  36.         }

  37.         return arr;
  38.     }
复制代码

作者: 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