在一个范围内生成 N 个随机且唯一的数字 [英] Generate N random and unique numbers within a range
问题描述
使用 C# 在给定范围内生成 N 个唯一数字的有效方法是什么?例如,生成 1 到 50 之间的 6 个唯一数字.一种懒惰的方法是在循环中简单地使用 Random.Next()
并将该数字存储在数组/列表中,然后重复并检查是否它已经存在与否等等.有没有更好的方法来生成一组随机但唯一的数字?为了添加更多上下文,我想使用它们的索引从集合中随机选择 N 个项目.
What is an efficient way of generating N unique numbers within a given range using C#? For example, generate 6 unique numbers between 1 and 50. A lazy way would be to simply use Random.Next()
in a loop and store that number in an array/list, then repeat and check if it already exists or not etc.. Is there a better way to generate a group of random, but unique, numbers?
To add more context, I would like to select N random items from a collection, using their index.
谢谢
推荐答案
取一个包含 50 个元素的数组:{1, 2, 3, .... 50}
使用随机混洗数组的任何标准算法对数组进行混洗.修改后的数组的前六个元素就是您要查找的内容.HTH
Take an array of 50 elements: {1, 2, 3, .... 50}
Shuffle the array using any of the standard algorithms of randomly shuffling arrays. The first six elements of the modified array is what you are looking for. HTH
这篇关于在一个范围内生成 N 个随机且唯一的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!