class MyRand { private int seed; private int prevNumber = 10; public MyRand(int seed) { this.seed = seed; } public int Next() { int newRand = (seed + prevNumber) % 100; prevNumber = newRand; return newRand; } } List<int> list = new List<int>(); Random rand = new Random(); while (list.Count < 100) { int number = rand.Next(1, 101);//>=1,<101 if (!list.Contains(number))//如果list中已经含有这个数,则不插入 { list.Add(number); } } foreach (int i in list) { Console.WriteLine(i); }
原理 r(n) = (sed + r(n - 1)) % 100;
做法2:先把1-100这100个数按顺序放入数组arr,再重复100次下面的操作,生成两个介于 >=0,<100 之间的随机数m、n,颠倒arr[m]和arr[n]的数。
int[] arr = new int[100]; //把100个数顺序放入 for (int i = 0; i < 100; i++) { arr[i] = i + 1; } Random rand = new Random(); for (int i = 0; i < 2; i++) { int m = rand.Next(0, 100); int n = rand.Next(0, 100); if (m != n) { int temp = arr[m]; arr[m] = arr[n]; arr[n] = temp; } Console.WriteLine(arr[m] + " " + arr[n]); }
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; }