class UniqueRandom : Random
{
Dictionary<int, int> _tbl = new Dictionary<int, int>();
new public int Next()
{
int ret = base.Next();
while (_tbl.ContainsKey(ret))
{
ret = base.Next();
}
_tbl.Add(ret, 0);
return ret;
}
new public int Next(int maxValue)
{
if (_tbl.Count >= maxValue)
{
throw new Exception("Overflow!");
}
int ret = base.Next(maxValue);
while (_tbl.ContainsKey(ret))
{
ret = base.Next(maxValue);
}
_tbl.Add(ret, 0);
return ret;
}
new public int Next(int minValue, int maxValue)
{
if (_tbl.Count >= maxValue - minValue)
{
throw new Exception("Overflow!");
}
int ret = base.Next(minValue, maxValue);
while (_tbl.ContainsKey(ret))
{
ret = base.Next(minValue, maxValue);
}
_tbl.Add(ret, 0);
return ret;
}
}
static void Main(string[] args)
{
UniqueRandom rand = new UniqueRandom();
for (int i = 0; i < 100; i++)
{
Console.WriteLine(rand.Next(100));
}
}
下面是改用 HashSet的,比Dictionaly 要好,但必须是 .Net3.5才能支持
using System;
using System.Collections.Generic;
using System.Text;
namespace TestConsole
{
class UniqueRandom : Random
{
System.Collections.Generic.HashSet<int> _tbl = new HashSet<int>();
new public int Next()
{
int ret = base.Next();
while (_tbl.Contains(ret))
{
ret = base.Next();
}
_tbl.Add(ret);
return ret;
}
new public int Next(int maxValue)
{
if (_tbl.Count >= maxValue)
{
throw new Exception("Overflow!");
}
int ret = base.Next(maxValue);
while (_tbl.Contains(ret))
{
ret = base.Next(maxValue);
}
_tbl.Add(ret);
return ret;
}
new public int Next(int minValue, int maxValue)
{
if (_tbl.Count >= maxValue - minValue)
{
throw new Exception("Overflow!");
}
int ret = base.Next(minValue, maxValue);
while (_tbl.Contains(ret))
{
ret = base.Next(minValue, maxValue);
}
_tbl.Add(ret);
return ret;
}
}
}
Code
IList<int> list = new List<int>();
Random rd = new Random();
for (int i = 0; i < 100; i++)
{
int num = rd.Next(0, 100);
if (!list.Contains(num))
{
list.Add(num);
}
}
foreach (int i in list)
{
Console.WriteLine(i);
}
使用HashSet<T>数据类型即可
发个简单点的吧
/// <summary>
/// 生成随机的字母
/// </summary>
private string RndNum(int VcodeNum)
{
string Vchar = "0,1,2,3,4,5,6,7,8,9";
string[] VcArray = Vchar.Split(',');
string VNum = "";
int temp = -1;
Random rand = new Random();
for (int i = 1; i < VcodeNum + 1; i++)
{
if (temp != -1)
{
rand = new Random(i * temp * unchecked((int)DateTime.Now.Ticks));
}
int t = rand.Next(VcArray.Length);
if (temp != -1 && temp == t)
{
return RndNum(VcodeNum);
}
temp = t;
VNum += VcArray[t];
}
return VNum;
}
public static Array NoRepeatInsert()
{
System.Collections.ArrayList arrlist = new System.Collections.ArrayList();
int[] arr = new int[100];
Random rdm = new Random();
for (int i = 0; i < 100; i++)
{
//arrlist[i] = i + 1;
arrlist.Add(i + 1);
}
for (int j = 0; j <100; j++)
{
int index = rdm.Next(arrlist.Count);//0~arrlist.Count-1
arr[j] =Convert.ToInt32(arrlist[index]);
arrlist.RemoveAt(index);//At
}
return arr;
}