之分享过一个生成随机不重复数组的一个算法,感觉不太完善,有一点缺陷。这里重新分享一个新的。核心代码如下如下:
using System;
using System.Collections;
using System.Collections.Generic;
public class RandomIndex {
//单实例模式
private static RandomIndex _instance;
public static RandomIndex Instance {
get {
if (_instance == null) {
_instance = new RandomIndex ();
}
return _instance;
}
}
/// <summary>
/// 创建一个不重复的随机数组
/// </summary>
/// <param name="maxSeedLength">取随机值的最大值</param>
/// <param name="returnLength">返回元素的个数</param>
/// <returns></returns>
public int[] CreateRandomNmber (int maxSeedLength, int returnLength) {
List<int> list = new List<int> ();
System.Random rd = new System.Random ();
for (int i = 0; i < returnLength; i++) {
int temp = rd.Next (0, maxSeedLength);
while (list.Contains (temp)) {
temp = rd.Next (0, maxSeedLength);
}
list.Add (temp);
}
return list.ToArray ();
}
}
添加一个测试类如下:
using System;
namespace temp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
int[] temp=RandomIndex.Instance.CreateRandomNmber(20,5);
foreach(var i in temp){
System.Console.WriteLine(i);
}
}
}
}
输出如下所示:
更多内容欢迎关注: