pieguy
pieguy

Reputation:

How do I make a function happen 50% of the time in vb6

Making a small app, and I want a function to execute 50% of the time. So if I were to dbl click the exe half the time the function would execute, and the other half it wouldn't. I can't seem to find anyway to easily do this, the one solution I tried seemed to determine the chance on compile rather than on run. Thanks in advance!

Upvotes: 0

Views: 241

Answers (4)

Alex Warren
Alex Warren

Reputation: 7547

Don't forget to seed the randomizer! Otherwise it will always give you the same value every time. You seed it using "Randomize Timer", e.g.:

Private Sub Main()
    Randomize Timer
    If Rnd > 0.5 Then
        ExecuteFunction ()
    End If
End Sub

Upvotes: 4

paxdiablo
paxdiablo

Reputation: 882028

If you want it to randomly run, others have already provided that solution. If you want a more deterministic behavior (it must run exactly every second time), you will need to store state between executions.

You can save the state in either the registry or on the file system by (for example) attempting to read an integer from a file (set it to zero if the file's not there), add 1 and write it back to the same file.

If the number written back was even, run your function otherwise exit.

That way, you'll alternate between execute and don't-execute.

Upvotes: 1

Nescio
Nescio

Reputation: 28433

For example:

Private Sub Main()
    If Rnd > 0.5 Then
        ExecuteFunction ()
    End If
End Sub

Upvotes: 2

Mitch Wheat
Mitch Wheat

Reputation: 300719

Generate a random decimal number between 0 and 1. If it is greater than 0.5 run, if it is less than or equal to 0.5 do not run.

Upvotes: 4

Related Questions