随机填充数组,不重复

时间:2013-02-14 22:06:08

标签: c# recursion repeat

我正在尝试用1-10中的随机数填充数组而不重复。我尝试用递归来做。我正在尝试使用递归和没有(这两者都没有,无论如何都没有运气)。我有两个代码,两个都不起作用:

1:

static int reco(int arr,int[] times)
{
    Random rnd = new Random();
    arr = rnd.Next(1, 11);
    return times[arr] > 0 ? reco(arr, times) : arr;
}

static void Main(string[] args)
{
    int i = 0;
    int[] arr = new int[10];
    int[] times = new int[11];
    Random rnd = new Random();

    for (i = 0; i < 10; i++)
    {
        arr[i] = rnd.Next(1, 11);
        times[arr[i]]++;

        if (times[arr[i]] > 0)
            arr[i] = reco(arr[i], times);
    }

2:

static int reco(int arr,int[] times)
{
    Random rnd = new Random();
    arr = rnd.Next(1, 11);
    if (times[arr] > 0)
        return reco(arr, times);
    else
        return arr;
}
static void Main(string[] args)
{
    int i = 0;
    int[] arr = new int[10];
    int[] times = new int[11];
    Random rnd = new Random();
    for (i = 0; i < 10; i++)
    {
        arr[i] = rnd.Next(1, 11);

        if (times[arr[i]] > 0)
            arr[i] = reco(arr[i], times);

        times[arr[i]]++;
    }
}

5 个答案:

答案 0 :(得分:4)

如果你只想要1到10之间的随机数,你可以使用Enumerable.Range并随机排序。

var ran = new Random();
int[] randomArray = Enumerable.Range(1, 10).OrderBy(x => ran.Next()).ToArray();

答案 1 :(得分:2)

在特定范围内生成唯一的“随机”数字,如:

List<int> theList = Enumerable.Range(0, 10).ToList();
theList.Shuffle();

示例输出:

[1,5,4,8,2,9,6,3,7,0]

随机播放功能(来源:Randomize a List<T>):

public static void Shuffle<T>(this IList<T> list)  
{  
    Random rng = new Random();  
    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;  
    }  
}

答案 2 :(得分:1)

由于您正在使用C#,并且您知道数组中的随机数,为什么不创建数组,然后随机化位置?这是一个例子:

using System.Linq;

//......

Random rand = new Random();
int[] randomNumbers = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
randomNumbers.OrderBy(num => rand.Next());

答案 3 :(得分:0)

    static void Main()
    {
        int[] arr = new int[10];
        List<int> numbers = Enumerable.Range(1, 10).ToList();
        Random rnd = new Random();
        for (int i = 0; i < 10; i++)
        {
            int index = rnd.Next(0, numbers.Count - 1);
            arr[i] = numbers[index];
            numbers.RemoveAt(index);
        }
    }

答案 4 :(得分:0)

你可以这样做。递归版本留作原始海报的练习,因为这个问题听起来像是一个家庭作业:

int[] arr = new int[10];

// Fill the array with values 1 to 10:
for (int i = 0; i < arr.Length; i++)
{
    arr[i] = i + 1;
}

// Switch pairs of values for unbiased uniform random distribution:
Random rnd = new Random();
for (int i = 0; i < arr.Length - 1; i++)
{
    int j = rnd.Next(i, arr.Length);

    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}

这使用Eric Lippert在下面的评论中提出的Fisher-Yates (Knuth) shuffle