什么是用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 elemwnts数组: {1,2,3,... 50}
洗牌使用任何随机洗牌阵列的标准算法的数组。修改后的数组的第一个六要素就是你所期待的。心连心
Take an array of 50 elemwnts: {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
相关推荐
最新文章