在指定范围内快速地产生随机数
问题如题,解决方案如下:
1
using System;2
using System.Collections.Generic;3
using System.Linq;4
using System.Text;5

6
namespace RandN7


{8
class Program9

{10
static void Main(string[] args)11

{12
int[] array = Random100();13
foreach (int i in array)14
Console.WriteLine(i);15
Console.WriteLine();16
}17

18

/**//// <summary>19
/// 算法描述如下:20
/// 1.在1-i(1<i<=101,初值为101)之间随机产生一个数,作为动态数组的下标21
/// 2.取动态数组在1中产生下标对应的数,存入返回数组中,动态数组删除该数22
/// 3.i自减1,继续执行第1个步骤。23
/// 4.当i<=1时退出循环24
/// </summary>25
/// <returns></returns>26
public static int[] Random100()27

{28
int[] array = new int[100];29
List<int> list = new List<int>();30
Random r = new Random();31
int index = -1;32

33
for (int i = 1; i <= 100; ++i)34
list.Add(i);35

36
for (int i = 101; i > 1; --i)37

{38
//产生1-i之间的索引39
index = r.Next(1, i) - 1;40

41
//取数,存入返回数组42
array[i - 2] = list[index];43

44
//在动态数组中删除45
list.RemoveAt(index);46
}47

48
return array;49
}50
}//End class51
}
浙公网安备 33010602011771号