how can i break an integer to three random pieces(e.g. for 800; 300,225,275) in VB?
Printable View
how can i break an integer to three random pieces(e.g. for 800; 300,225,275) in VB?
Pick a random number from 1 to 800 - that's the first bite.Quote:
Originally Posted by kill_bill_gates
Subtract that from the value - let's say 300 was first pick.
Remaining value is now 500.
Pick a random number from 1 to 500 - that's the second bite.
Subtract that from the value - let's say it's 225 like your example.
This leaves you with 275.
Quote:
Originally Posted by kill_bill_gates
VB Code:
Public Sub Split3Parts(ByVal value As Integer, ByRef a As Integer, ByRef b As Integer, ByRef c As Integer) Dim r As Random = New Random Dim x, y, z As Integer x = r.Next(0, value + 1) y = r.Next(0, value + 1) If x > y Then z = x x = y y = z End If a = x b = Math.Abs(x - y) c = Math.Abs(value - y) End Sub
Seems to work ok, inserts values BYREF into a, b and c. Doesn't neccessarily give results in numerical order.
Can easily be modified to return a sorted array.
To show it works... (put this in a button click event)
VB Code:
Dim a, b, c As Integer Split3Parts(800, a, b, c) Me.Text = a & " " & b & " " & c & " " & "(total: " & (a + b + c) & ")"