c語言取隨機數不重複:c生成隨機數不重複

c sharp調用Random類生成不重複的隨機數的方法

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://www.506064.com/zh-hant/n/223229.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
投稿專員的頭像投稿專員
上一篇 2024-12-09 14:15
下一篇 2024-12-09 14:15

相關推薦

發表回復

登錄後才能評論