Picking random guys
Ron just asked me to demo how I thought the Random guy selector would be implemented so, I thought I'd crank out a quickie demo. First, I'll create a Guy type:
Class Guy
Private mName As String
Private mScore As Integer
Public Sub New(ByVal name As String, ByVal score As Integer)
Me.mName = name
Me.mScore = score
End Sub
Public ReadOnly Property Name() As String
Get
Return mName
End Get
End Property
Public ReadOnly Property Score() As Integer
Get
Return mScore
End Get
End Property
Public Overrides Function ToString() As String
Return Me.mName & " ( " & Me.mScore & " ) "
End Function
End Class
This example populates a collection of guys on init of a process and then handles an event to randomly select a guy from the collection. Using the logic mentioned in the previous post, a guy with a higher "Score" should have a higher probability of pushing the randomly generated target below zero:
Private mGuys As New ArrayList
Private mSumOfGuys As Integer
Private Sub InitailizeGuys(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim names As String() = {"Jim", "Bob", "Wayne", "Foo", "Darren", "Barry"}
Dim r As New Random
For Each s As String In names
Dim guy As New Guy(s, r.Next(100))
mGuys.Add(guy)
mSumOfGuys += guy.Score
LabelGuys.Text &= guy.ToString & vbCrLf
Next
End Sub
Private Sub PickARandomGuy(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GetRandomGuyButton.Click
Dim r As New Random
Dim randScore As Integer = r.Next(mSumOfGuys)
For Each g As Guy In mGuys
randScore -= g.Score
If randScore <= 0 Then
LabelRandomGuy.Text = "New guy is : " & g.ToString
Exit Sub
End If
Next
End Sub
Here's Ron's results (formatted). I ran a test picking a "Guy" 10000000 times and here is the result:
Player Weight Weighted Probability Occurance (10000000 iterations)
====== ====== ===================== ===============================
Jim 20 05.87 06.34
Bob 10 02.93 03.02
Wayne 40 11.73 11.91
Foo 5 01.47 01.48
Darren 90 26.39 26.35
Barry 22 06.45 06.57
Randy 45 13.20 13.36
John 11 03.23 03.11
Doe 98 28.74 27.86