/// <summary>
/// 产生不重复的随机数
/// </summary>
/// <param name="as_arrNums">元素不重复的数组</param>
/// <param name="as_temp">临时数</param>
/// <param name="as_minNum">最小值</param>
/// <param name="as_maxNum">最大值</param>
/// <param name="as_random">Random对象</param>
/// <returns></returns>
public static int getRanNumber(int[] as_arrNums, int as_temp, int as_minNum, int as_maxNum, Random as_random)
{
int ls_row = 0;
while (ls_row < as_arrNums.Length)
{ //循环遍历数组如果有重复的则重新取值
//数组元素默认值为0 所以第1次传入的as_temp的值为0会重新取值
if (as_temp == as_arrNums[ls_row])
{
as_temp = as_random.Next(as_minNum, as_maxNum);
as_temp = getRanNumber(as_arrNums, as_temp, as_minNum, as_maxNum, as_random);
}
ls_row++;
}
return as_temp;
}
public static int[] get_ranNumbers(int as_count)
{
Random ran = new Random();
int[] nums = new int[as_count];
int ls_int = 0;
for (int i = 0; i < nums.Length; i++)
{
ls_int = getRanNumber(nums, ls_int, 1, 11, ran);
nums[i] = ls_int;
}
return nums;
}
static void Main(string[] args)
{
int[] nums = get_ranNumbers(10);
foreach (int num in nums) {
Console.WriteLine(num);
}
Console.ReadKey();
运行结果 我测试过ok |