-1

我想在 c# 中用 0-9 之间的唯一随机数填充我的数组我尝试这个函数:

    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);
}

但我得到了错误:

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<int>' to 'int'

我还添加了这个命名空间:

using System.Collections.Generic;

我只是不知道如何将函数输出转换为int ...请帮助我...谢谢...

4

4 回答 4

4

你最好做这样的事情,使用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();
于 2012-05-21T15:23:17.637 回答
2

您的方法返回一个可枚举,但您尝试分配一个值。一步分配所有值:

int[] page = UniqueRandom(0, 9).Take(3).ToArray();  // instead of your loop

编辑:根据您的评论,我判断您可能在不理解的情况下复制了您向我们展示的代码。也许你想用可能重复的随机数填充你的数组(例如1, 6, 3, 1, 8, ...)?您当前的代码仅使用每个值一次(因此名称为unique),因此您不能用它填充大小大于 10 的数组。

如果您只想要简单的随机数,则根本不需要这种方法。

var rnd = new Random();

// creates an array of 100 random numbers from 0 to 9
int[] numbers = (from i in Enumerable.Range(0, 100) 
                 select rnd.Next(0, 9)).ToArray();
于 2012-05-21T15:25:03.843 回答
1

你可以这样做:

int i = 0;
foreach (int random in UniqueRandom(0, 9).Take(3))
{
    page[i++] = random;
}
于 2012-05-21T15:22:48.277 回答
0

我的数组太大了,我需要很多随机数......当我使用

 int[] page = UniqueRandom(0, 9).Take(arraysize).ToArray(); 

它给了我正好 9 个唯一的随机数..

我得到了这个错误(例如对于arraysize = 15):

index was outside of bounds of array

我怎样才能有一个在 0-9 之间有太多随机数的数组而不重复?

于 2012-05-22T06:18:25.907 回答