确保特定数字在随机数集中 [英] Guarantee a specific number is in a random number set

查看:112
本文介绍了确保特定数字在随机数集中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了代码,该代码随机生成数字并将其存储在哈希集中,以防止重复.但是,每次运行生成器时,我都需要生成一个特定的数字以及其他一些数字,然后将所有值(包括我想要生成的数字)以随机顺序存储在哈希集中.

I have written code which randomly generates number and stores them in a hashset to prevent duplicates. However, each time i run the generator i need to generate a specific number as well as some other numbers and then store all the values including the number i wanted generated stored in a hashset in a random order.

做到这一点的最佳方法是什么?

What would be the best way to do this?

推荐答案

一系列没有重复的值通常表示随机播放,因为值可以在一系列随机值中重复.我不知道值的范围是多少,所以我会猜.这比循环中的哈希集更容易:

A series of values with no repeats generally means a shuffle because a value can repeat in a series of random values. I dont know what the range of values is, so I will guess. This is easier than a hashset in a loop:

' use the same random object over and over
Private rng As New Random()
...
Dim MustHave As Int32 = 42

Dim values = Enumerable.Range(1, 100).
      OrderBy(Function(r) rng.Next()).
      Take(10).ToArray()

' it might already be in the set, so check
If values.Contains(MustHave) = False Then
    values(rng.Next(0, values.Length)) = MustHave
End If

第一部分的说明:

  • Enumerable 是一种类型,具有用于求和,平均值等的共享方法.该代码使用 Range 创建从1开始的100个值.设置的值来自.
  • 接下来,使用创建的 Random 对象将内容随机排列
  • Take 是另一个 IEnumerable 方法,用于返回 n 个元素;在这里,10.
  • 最后,将它们(幸运的10个)放到一个数组中
  • Enumerable is a Type with gobs of Shared methods to Sum, Average etc. The code uses Range to create 100 values starting at 1. This is to be the pool the value set comes from.
  • Next, the contents are put in random order using the Random object created
  • Take is another IEnumerable method to return n elements; here, 10.
  • Finally, put them (the lucky 10) into an array

最后一步将要显示的值放在一个随机位置之前,尚不存在.

The last step checks that the value you want to appear, isn't already there before putting it in a random spot.

使用 OrderBy 将它们随机排列通常是一个简单而足够的随机播放.另外,也可以使用此处显示的 Fisher-Yates随机播放.它更长,但效率更高.

Using OrderBy to put them in a random order is often a simple-good-enough shuffle. Alternatively, use the Fisher-Yates shuffle shown here. Its longer, but more efficient.

这篇关于确保特定数字在随机数集中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆