[英]How to generate N random ints from 0 to num in C# efficiently?
我能夠編寫一個可以在一定范圍內生成“唯一&&隨機”整數的函數。 但這在n 2中 。 我在一處將它用於6個隨機整數,而在另一處將其用於30個隨機整數,那么如果需要改進它,我們如何才能對其進行改進?
private int[] genRands(int max, int totalRandomIntsRequired)
{
int[] nums = new int[totalRandomIntsRequired];
Random r = new Random();
for (int i = 0; i < totalRandomIntsRequired; i++)
{
nums[i] = r.Next(0, max + 1);
for (int j = i; j >= 0; j--)
{
if(nums[i] == nums[j])
{
nums[i] = r.Next(0, max + 1);
}
}
}
return nums;
}
這是使用HashSet
的方法,該方法不允許重復,並且是有效的內部重復檢查。
public static int[] genRands(int total, int max)
{
if (max < total)
{
throw new IndexOutOfRangeException();
}
Random _random = new Random();
HashSet<int> Result = new HashSet<int>();
while (Result.Count < total)
{
Result.Add(_random.Next(0, max));
}
return Result.ToArray();
}
我對您要問的內容有些困惑,如果只需要生成6個或n個隨機數,為什么要循環兩次? 無論哪種方式,您都可以嘗試一下
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
var rands = genRands(100, 6);
foreach (var num in rands.Select((n, i) => new { i= i + 1, n }))
{ Console.WriteLine(string.Format("[{0}] {1}", num.i, num.n));};
Console.ReadLine();
}
private static List<int> genRands(int max, int total)
{
var nums = new List<int>();
Random r = new Random();
for (int i = 0; i < total; i++)
nums.Add(r.Next(0, max));
return nums;
}
}
}
它應該輸出這樣的東西
[1] 45
[2] 29
[3] 40
[4] 75
[5] 29
[6] 57
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.