在C#中填充0-9之间,潮头随机数的数组 [英] filling a array with uniqe random numbers between 0-9 in c#
本文介绍了在C#中填充0-9之间,潮头随机数的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要填写我的数组在C#
0-9独特的随机数我试试这个功能:
I want to fill my array with unique random numbers between 0-9 in c# I try this function:
IEnumerable<int> UniqueRandom(int minInclusive, int maxInclusive)
{
List<int> candidates = new List<int>();
for (int i = minInclusive; i <= maxInclusive; i++)
{
candidates.Add(i);
}
Random rnd = new Random();
while (candidates.Count > 1)
{
int index = rnd.Next(candidates.Count);
yield return candidates[index];
candidates.RemoveAt(index);
}
}
和我使用它是这样的:
for (int i = 0; i < 3; i++)
{
page[i] = UniqueRandom(0, 9);
}
但我得到了错误:
But I got error :
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<int>' to 'int'
我也添加了这个名字空间:
I also added this name space:
using System.Collections.Generic;
我只是不知道我怎么能转换函数输出为int ...请帮助我...谢谢...
I just don't know how I can convert the function output to int... please help me... thank you...
推荐答案
您是好得多做这样的事情,使用的费 - 耶茨洗牌:
You're much better off doing something like this, using a Fischer-Yates shuffle:
public static void Shuffle<T>(this Random rng, IList<T> list)
{
int n = list.Count;
while (n > 1) {
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
的用法:的
var numbers = Enumerable.Range(0, 10).ToList(); // 0-9 inclusive
var rng = new Random();
rng.Shuffle(numbers);
int[] page = numbers.Take(3).ToArray();
这篇关于在C#中填充0-9之间,潮头随机数的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文