我们来看一个实例:

有一个一维数组,一共有10个元素,如何生成非负随机数来填充这个数组。
也就是说,我们如何生成10个不重复的非负数。如果我们直接用随机数的方式来做,肯定不行。
因为,理论上来讲,无论如何,这10个数,始终存在重复数的可能,只是概率的高低而已。
那么,我们如何生成真正不重复随机数了?

我这里的原理是这样:
1.设定一个数组,用来保存原始的非负数,这个数组的大小可以根据需要进行设定。这里设定为100,数组名为intTempArr。再设定一个数组,用来保存生成的无重复随机数,我们设定为:intArr,大小为10。
2.循环填充数组intTempArr,intTempArr中的数字为非负数,且不重复。我们设定intTempArr中的数字为:101-200。
2.随机生成一个在以上数组大小范围内的非负数(我们设定为:temp。也就是说随机生成一个数的范围为:0-99。
3.用以上的随机数temp为索引,得到数组intTempArr[temp]的值,我们设定为:tempValue。
4.将tempValue赋值给intArr,从数组intTempArr中删除值为tempValue的元素,也就是删除索引为temp的值。这样,下次生成随机数时,这个数字就永远也不会出现了。
5.重复以上2,3步,我们就可以实现无重复的随机数了。


下面是代码:
代码
public void getRand()
{
            Random rd 
= new Random();
            ArrayList intTempArr 
= new ArrayList();
int[] intArr = new int[10];

//填充数组intTempArr
for (int i = 101; i < 200; i++)
{
                intTempArr.Add(i);
}

//生成随机数
for (int j = 0; j < intArr.Length; j++)
{
int temp = rd.Next(intTempArr.Count-1);
int tempValue = (int)intTempArr[temp];
                intArr[j] 
= tempValue;
                intTempArr.RemoveAt(temp);
                Console.Write(
"intArr[" + j + "]=" + tempValue + "\n\r");
}
}

 

posted on 2010-03-25 10:42  arong.NET  阅读(918)  评论(0编辑  收藏  举报