You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core Web API实现无重复随机抽5道问题的方案咨询

解决.NET Core Web API中随机抽取不重复问题的方法

核心问题分析

你遇到的重复问题,通常是因为每次生成随机数时都创建了新的Random实例。Random默认用系统时钟作为种子,短时间内多次实例化会导致种子重复,进而生成相同的随机序列,出现重复抽取的情况。

可行解决方案

方案1:Fisher-Yates洗牌算法(推荐)

这是生成无重复随机子集的经典算法,效率高且逻辑清晰。步骤是:先创建包含1-50的完整列表,通过洗牌打乱顺序,再取前5个元素。

代码示例:

// 确保Random实例是单例(避免重复种子)
private static readonly Random _random = new Random();

public List<int> GetRandomQuestions()
{
    var questionIds = Enumerable.Range(1, 50).ToList();
    
    // Fisher-Yates洗牌
    for (int i = questionIds.Count - 1; i > 0; i--)
    {
        int j = _random.Next(i + 1);
        (questionIds[i], questionIds[j]) = (questionIds[j], questionIds[i]);
    }
    
    // 取前5个不重复的ID
    return questionIds.Take(5).ToList();
}

方案2:动态移除已选元素

维护一个候选ID集合,每次随机抽取一个后从集合中移除,直到抽到5个元素。这种方法适合不想打乱整个列表的场景。

代码示例:

private static readonly Random _random = new Random();

public List<int> GetRandomQuestions()
{
    var candidateIds = new List<int>(Enumerable.Range(1, 50));
    var selectedIds = new List<int>();
    
    for (int i = 0; i < 5; i++)
    {
        int index = _random.Next(candidateIds.Count);
        selectedIds.Add(candidateIds[index]);
        candidateIds.RemoveAt(index);
    }
    
    return selectedIds;
}

关键注意事项

  • 单例Random实例:必须确保整个应用中Random实例是唯一的,不要在每次生成随机数时新建实例。可以把它定义为静态字段,或者通过依赖注入注册为单例。
  • 避免在循环内实例化Random:如果在循环里每次都new Random(),极大概率会生成重复的随机数。

内容的提问来源于stack exchange,提问作者John Smit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 15:25:44