繁花不似锦
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; } }}