C#中随机数生成技巧有哪些

   2024-09-30 2700
核心提示:在C#中,生成随机数的常用方法是使用System.Random类使用单个随机数生成器:为了避免在短时间内创建多个随机数生成器实例(可能

在C#中,生成随机数的常用方法是使用System.Random

使用单个随机数生成器:为了避免在短时间内创建多个随机数生成器实例(可能导致重复的随机数),可以使用一个静态的随机数生成器。
public static class RandomHelper{    private static readonly Random _random = new Random();    public static int GetRandomNumber(int min, int max)    {        return _random.Next(min, max);    }}
使用System.Security.Cryptography.RNGCryptoServiceProvider生成密码学安全的随机数:当需要生成加密安全的随机数时,可以使用RNGCryptoServiceProvider类。
using System.Security.Cryptography;public static class CryptoRandomHelper{    public static int GetCryptoRandomNumber(int min, int max)    {        using var rng = new RNGCryptoServiceProvider();        var randomNumber = new byte[4];        rng.GetBytes(randomNumber);        int fullRange = max - min;        int result = BitConverter.ToInt32(randomNumber, 0) % fullRange + min;        return result;    }}
生成正态分布的随机数:可以使用Random.NextGaussian扩展方法生成正态分布的随机数。
public static class GaussianRandomHelper{    public static double NextGaussian(this Random random, double mean, double stdDev)    {        double u1 = random.NextDouble();        double u2 = random.NextDouble();        double randStdNormal = Math.Sqrt(-2.0 * Math.Log(u1)) * Math.Sin(2.0 * Math.PI * u2);        return mean + stdDev * randStdNormal;    }}
生成不重复的随机数序列:如果需要生成一个不包含重复元素的随机数序列,可以使用Fisher-Yates算法对一个有序的整数序列进行随机排序。
public static class UniqueRandomNumbersHelper{    public static IEnumerable<int> GetUniqueRandomNumbers(int count, int min, int max)    {        if (count > max - min + 1)            throw new ArgumentOutOfRangeException(nameof(count), "Count is too large.");        var numbers = Enumerable.Range(min, max - min + 1).ToList();        var random = new Random();        for (int i = numbers.Count - 1; i >= 0; i--)        {            int j = random.Next(i + 1);            yield return numbers[j];            numbers[j] = numbers[i];        }    }}

这些技巧可以帮助你在C#中更高效地生成随机数。

 
举报打赏
 
更多>同类网点查询
推荐图文
推荐网点查询
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号