c sharp调用Random类生成不重复的随机数的方法
方法1:数组来保存索引号,先随机生成一个数组位置
//产生不重复的随机数
namespace ArrayRandTwo
{
class Program
{
static void Main(string[] args)
{
int[] a = new int[15];
for (int i = 0; i < a.Length ; i++)
a[i] = i;
Random r = new Random();
//新的数组result用来保存随机生成的不重复的10个数
int[] result = new int[10];
//设置上限
int ulimit = 15;
int id;
for (int j = 0; j < 10; j++)
{
id = r.Next(1, ulimit - 1);
//在随机位置取出一个数,保存到结果数组
result[j] = a[id];
//最后一个数复制到当前位置
a[id] = a[ulimit - 1];
//位置的上限减少一
ulimit--;
}
foreach (int k in result)
{
Console.Write("{0} ", k);
}
Console.ReadKey();
}
}
}
方法2: 利用Hashtable
必须引进空间名:using System.Collections; Hashtable中文称作哈希表,也叫散列表,是根据key和value进行访问存储的数据结构
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//Hashtable的命名空间System.Collections,通过using进行引入。
namespace ArrayRandThree
{
class Program
{
static void Main(string[] args)
{
//实例化Hashtable
Hashtable hashtable = new Hashtable();
Random rm = new Random();
int RmNum = 100;
for (int i = 0; hashtable.Count < RmNum; i++)
{
//产生随机数给nValue
int nValue = rm.Next(100);
if (!hashtable.ContainsValue(nValue) && nValue != 0)
{
增加元素nValue
hashtable.Add(nValue, nValue);
//value的遍历
foreach (int value in hashtable.Values)
{
Console.WriteLine(value);
}
}
Console.ReadKey();
}
}
}
}
方法3:List 类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ArrayRandFour
{
class Program
{
static void Main(string[] args)
{
List<int> listNum = new List<int>();
Random random = new Random();
//最小随机数
const int Min = 100;
//最小随机数
const int Max = 999;
//产生多少个随机数,这里是10个
const int Count = 10;
for (int i = 0; i < 100; i++)
{
var num = random.Next(Min, Max);
if (!listNum.Contains(num))
{
//将产生的随机数num添加到listNum尾部
listNum.Add(num);
//判断 达到设定的Count,跳出循环
if (listNum.Count == Count)
{
break;
}
}
}
//遍历 listNum
foreach (int k in listNum)
{
Console.Write("{0} ", k);
}
Console.ReadKey();
}
}
}