问题
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:
Enumerableis a Type with gobs of Shared methods to Sum, Average etc. The code usesRangeto 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
Randomobject created Takeis anotherIEnumerablemethod to returnnelements; 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