实现原理:
方法1:使用list,通过list.contains()作为循环判断的条件,实现无重复的add
方法2:使用两组数组,all存储所有可取值,result存储结果,result依次从all中取值,all长度递减,通过索引实现all中始终保持取完后剩下的元素
分析:法1在最坏情况下会重复循环,法2通过保证每次都能取到值,很大程度上提高了效率
代码比较:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; namespace 基本语法 { class Program { static void Main(string[] args) { Stopwatch watch = new Stopwatch(); watch.Start(); List<int> list = _GetRandom(20, 500, 400); watch.Stop(); int ctrl = 0; foreach (int i in list) { Console.Write("{0} ", i); ++ctrl; if (ctrl % 20 == 0) Console.WriteLine(); } Console.WriteLine("\nMethod 1 time used:{0}", watch.Elapsed); watch.Reset(); watch.Start(); int[] ia = GetRandom(20, 500, 400); watch.Stop(); ctrl = 0; foreach (int i in ia) { Console.Write("{0} ", i); ++ctrl; if (ctrl % 20 == 0) Console.WriteLine(); } Console.WriteLine("\nMethod 2 time used:{0}", watch.Elapsed); } /// <summary> /// 使用list容器产生一定范围内互不相同的随机数 /// </summary> /// <param name="minVal">最小值</param> /// <param name="maxVal">最大值</param> /// <param name="amount">随机数总数</param> /// <returns>返回list<int></returns> static List<int> _GetRandom(int minVal, int maxVal, int amount) { List<int> list = new List<int>(); while (list.Count != amount) { Random random = new Random((int)DateTime.Now.Ticks); int temp = random.Next(minVal, maxVal); if (!list.Contains(temp)) list.Add(temp); } return list; } /// <summary> /// 使用数组方法实现 /// </summary> /// <param name="minVal"></param> /// <param name="maxVal"></param> /// <param name="amout"></param> /// <returns>返回int[]</returns> static int[] GetRandom(int minVal, int maxVal, int amout) { int[] result = new int[amout]; int[] all = new int[maxVal-minVal+1]; for (int ix = 0; ix!=amout;++ix ) { all[ix] = minVal + ix; } Random random = new Random(); int allNum = all.Length; for (int ix = 0; ix != amout;++ix ) { int index=random.Next(allNum); result[ix] = all[index]; all[index] = all[--allNum]; } return result; } } }
运行结果:
方法1在很多情况下耗时根本无法接受。。。