tags:

views:

161

answers:

4

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!

+4  A: 

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.

Mitch Wheat
+2  A: 

For example:

Private Sub Main()
    If Rnd > 0.5 Then
        ExecuteFunction ()
    End If
End Sub
Nescio
+1  A: 

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.

paxdiablo
+4  A: 

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
Alex Warren