using System; using System.Collections.Generic; using System.Text; using System.Collections; namespace 產生N個不重複隨機數的兩個函數 { class Program { static void Main(string[] args) { DateTime d1 = System.DateTime.Now; int[] list1 = GetRandom1(1, 100000, 5000); TimeSpan dd1 = System.DateTime.Now - d1; DateTime d2 = System.DateTime.Now; int[] list2 = GetRandom2(1, 100000*100, 5000); TimeSpan dd2 = System.DateTime.Now - d2; //foreach (int i in list1) // Console.Write("{0},", i); //foreach (int ii in list2) // Console.Write("{0},", ii); Console.WriteLine("第一種方法,1-100000 裡取5000個用時:{0}", dd1.TotalMilliseconds); Console.WriteLine("第二種方法,1-100000*100裡取5000個用時:{0}", dd2.TotalMilliseconds); Console.WriteLine("判斷第二種方法裡是否有重複數,如果是5000就是沒有重複的:{0}",RemoveDup(list2).Length); Console.ReadKey(); } public static int[] RemoveDup(int[] myData) { if (myData.Length > 0) { Array.Sort(myData); int size = 1; for (int i = 1; i < myData.Length; i++) if (myData[i] != myData[i - 1]) size++; int[] myTempData = new int[size]; int j = 0; myTempData[j++] = myData[0]; for (int i = 1; i < myData.Length; i++) if (myData[i] != myData[i - 1]) myTempData[j++] = myData[i]; return myTempData; } return myData; } //方法1 public static int[] GetRandom1(int minValue, int maxValue, int count) { Random rnd = new Random(); int length = maxValue - minValue + 1; byte[] keys = new byte[length]; rnd.NextBytes(keys); int[] items = new int[length]; for (int i = 0; i < length; i++) { items[i] = i + minValue; } Array.Sort(keys, items); int[] result = new int[count]; Array.Copy(items, result, count); return result; } //方法2 public static int[] GetRandom2(int minValue, int maxValue, int count) { int[] intList = new int[maxValue]; for (int i = 0; i < maxValue; i++) { intList[i] = i + minValue; } int[] intRet = new int[count]; int n = maxValue; Random rand = new Random(); for (int i = 0; i < count; i++) { int index = rand.Next(0, n); intRet[i] = intList[index]; intList[index] = intList[--n]; } return intRet; } } }