2 回答
TA贡献1851条经验 获得超4个赞
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;
}
}
}
TA贡献1951条经验 获得超3个赞
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); }
- 2 回答
- 0 关注
- 338 浏览
添加回答
举报