简体   繁体   English

如何在C#中有效地生成从0到num的N个随机整数?

[英]How to generate N random ints from 0 to num in C# efficiently?

I was able to write a function that can generate "unique && random" integers within a range. 我能够编写一个可以在一定范围内生成“唯一&&随机”整数的函数。 But this in n 2 . 但这在n 2中 I'm using it for 6 random ints at one place and 30 random ints at other, so how can we improve it if there's a need to improve it? 我在一处将它用于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;
    }

here is a approach with a HashSet which does not allow duplicates and as a efficient internal duplicate check. 这是使用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();
}

I'm a little confused in what you are asking, if you just need to generate 6 or n random numbers, why loop twice? 我对您要问的内容有些困惑,如果只需要生成6个或n个随机数,为什么要循环两次? Either way you can try out this 无论哪种方式,您都可以尝试一下

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

It should output something like this 它应该输出这样的东西

[1] 45
[2] 29
[3] 40
[4] 75
[5] 29
[6] 57

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM