Guarantee a specific number is in a random number set

ぐ巨炮叔叔 提交于 2020-01-16 04:50:08

问题


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?


回答1:


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

Explanation of the first part:

  • 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.

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.



来源:https://stackoverflow.com/questions/34072893/guarantee-a-specific-number-is-in-a-random-number-set

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!