c生成随机数不重复_c语言取随机数不重复

c生成随机数不重复_c语言取随机数不重复,第1张

c生成随机数重复_c语言取随机数不重复 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(); } }}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/tougao/665230.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-18
下一篇 2022-04-18

发表评论

登录后才能评论

评论列表(0条)

保存