Darryl - 1 year ago 62
Vb.net Question

# Is there a better way to set the odds to generating a random number and controling the limits?

I am trying to do a game that has 20 rounds of play. I have assigned 0 thru 8 to represent the items in the game. I need the random number to be 90 percent of the time to be any number 0 thru 5. I need the numbers 6 and 7 to be 4 percent of the time. And, I need the 8 to be only 2 percent of the time. Below is the code I have and it works sometimes but often it generates way too many of the 6s, 7s, and 8's. The way I see the code is that it should be working most of the time correctly but does not. Is there a better way to control the random to get the percents I need to be more consistently?

``````' Get the random number position into array
Public Sub GetNumPositions(ByVal positions() As Integer)
' 20 rounds, each round 5 numbers
' we want 2 times (8), 4 times (6 and 7)
' 2% 8, 4% 6, 4% 7, and 90% times 0 thru 5
For i As Integer = 0 To positions.Length - 1
Dim p As Integer = rndNums.Next(100)

If p < 90 Then
positions(i) = p \ 15
ElseIf p < 94 Then
positions(i) = 6
ElseIf p < 98 Then
positions(i) = 7
Else
positions(i) = 8
End If
Next
End Sub
``````

Your code is just fine. Here is a method to test it. It gathers some numbers and calculates their frequency:

``````Sub Main()
Dim count = 100000000
Dim positions(count) As Integer
Dim frequencies(9) As Integer
GetNumPositions(positions)
For Each num In positions
frequencies(num) += 1
Next
For i As Integer = 0 To 8
Console.WriteLine(i & ": " & (100.0 * frequencies(i) / count) & " %")
Next
End Sub
``````

The result is:

``````0: 14.994567 %
1: 15.000016 %
2: 15.01366 %
3: 14.996542 %
4: 15.002074 %
5: 15.00325 %
6: 4.002246 %
7: 3.999337 %
8: 2.000603 %
``````

As you can see, the frequencies match your input distribution very closely.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download